【问题标题】:how to split JSON object using php如何使用 php 拆分 JSON 对象
【发布时间】:2018-04-15 16:43:36
【问题描述】:

我有这个数据:

        "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",

我想将 "score":"3 - 0" 拆分为 homescore = 3 和 awayscore = 0

谢谢

【问题讨论】:

  • 你走了多远?

标签: php json api


【解决方案1】:
$data =  json_decode($json,true);


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

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

【讨论】:

    【解决方案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.
    

    我在 cmets 中写信给你它是如何工作的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-03
      • 2018-02-23
      • 1970-01-01
      • 2020-12-19
      • 1970-01-01
      • 1970-01-01
      • 2016-09-05
      • 2016-06-02
      相关资源
      最近更新 更多