合并两个JSON数组,然后对它们进行排序

时间:2016-05-25 17:21:11

标签: php arrays json sorting

如何合并两个JSON arrays,然后对ID值进行排序,以便结果显示最低数字到最低数字?

例如,我在下面的脚本中所需的输出是:

  • 1 - Jimbo
  • 2 - Bob
  • 6 - Luke
  • 12 - Chris
  • 16 - Jonas
  • 36 - Sam

这是我的JSON数组:

$json1 ='
{
    "error": "trueee",
    "info": {
        "collections": [{
            "ID": "1"
            "Name": "Jimbo"
        }, {
            "ID": "36"
            "Name": "Sam"
        }, {
            "ID": "2",
            "Name": "Bob"
        }]
    }
}
';

$json2 ='
{
    "error": "trueee",
    "info": {
        "collections": [{
            "ID": "12"
            "Name": "Chris"
        }, {
            "ID": "6"
            "Name": "Luke"
        }, {
            "ID": "16"
            "Name": "Jonas"
        }]
    }
}
';

1 个答案:

答案 0 :(得分:1)

您需要从{json字符串merge数组ID。首先使用关联数组获取arr的json解码而不是使用array_column获取$json1 =' { "error": "trueee", "info": { "collections": [{ "ID": "1" }, { "ID": "36" }, { "ID": "2" }] } } '; $json2 =' { "error": "trueee", "info": { "collections": [{ "ID": "12" }, { "ID": "6" }, { "ID": "16" }] } } '; $arr1 = json_decode($json1, true); $arr2 = json_decode($json2, true); $arr1 = array_column($arr1['info']['collections'], "ID"); $arr2 = array_column($arr2['info']['collections'], "ID"); $arr = array_merge($arr1, $arr2); sort($arr); echo '<pre>'; print_r($arr); 的列,然后你需要合并这两个数组并最终对它们进行排序。

Online CheckLong Conversation

Array
(
    [0] => 1
    [1] => 2
    [2] => 6
    [3] => 12
    [4] => 16
    [5] => 36
)

<强>结果:

pandas == 0.17.1
pymongo == 3.2.1