Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/262.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用php拆分JSON对象_Php_Json_Api - Fatal编程技术网

如何使用php拆分JSON对象

如何使用php拆分JSON对象,php,json,api,Php,Json,Api,我有以下数据: "home_name":"Atletico Madrid", "away_name":"Levante", "score":"3 - 0", "ht_score":"1 - 0", "ft_score":"3 - 0", "et_score":"", "time":"FT", "league_id":"74", "status":"FIN

我有以下数据:

        "home_name":"Atletico Madrid",
        "away_name":"Levante",
        "score":"3 - 0",
        "ht_score":"1 - 0",
        "ft_score":"3 - 0",
        "et_score":"",
        "time":"FT",
        "league_id":"74",
        "status":"FINISHED",
        "added":"2018-04-15 14:11:01",
        "last_changed":"2018-04-15 16:09:02",
        "home_id":"26",
        "away_id":"28",
我想把“分数”分为“3-0”分为homescore=3和awayscore=0

谢谢


我在评论中给你写了一封信,告诉你它是如何工作的。

你走了多远?
$data =  json_decode($json,true);


$match = $data['data']['match'][0][score];
$match = str_replace(" ","",$match);

list($home, $away) = explode("-", $match, 2);
function splitScore($json) {
    // Check if json is an array
    if (!is_array($json))
        // if json is not array convert him to array
        $json = json_decode($json, true);
    // IF json decode return an error return false
    if (json_last_error() != JSON_ERROR_NONE)
        return false;
    // Split the score to two
    $val = preg_split('/^([0-9]+)\s+\-\s+([0-9]+)$/', $json['score']);
    // Delete `score` from json
    unset($json['score'])
    // Add the splited score
    $json['homescore'] = $val[0];
    $json['awayscore'] = $val[1];
    // Return JSON
    return $json;
}
// $json contains the data
$json = splitScore($json);
// Now $json contains the new data.