如何使用php拆分JSON对象

时间:2018-04-15 16:43:37

标签: 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":"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

由于

2 个答案:

答案 0 :(得分:1)

$data =  json_decode($json,true);


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

list($home, $away) = explode("-", $match, 2);

答案 1 :(得分:0)

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.

我在评论中写信告诉你它是如何运作的。