【问题标题】:Merge two JSON arrays and then sort them合并两个 JSON 数组,然后对它们进行排序
【发布时间】:2016-09-23 10:53:07
【问题描述】:

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

例如,我想要的下面脚本的输出是:

  • 1 - 金博
  • 2 - 鲍勃
  • 6 - 卢克
  • 12 - 克里斯
  • 16 - 乔纳斯
  • 36 - 山姆

这是我的 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"
        }]
    }
}
';

【问题讨论】:

    标签: php arrays json sorting


    【解决方案1】:

    您需要merge json 字符串中的数组。首先使用关联数组获取 arr 的 json 解码,而不是使用 array_column 获取 ID 的列,然后您需要合并两个数组,最后对它们进行排序。

    Online CheckLong Conversation

    $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);
    

    结果:

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

    【讨论】:

    • 我从 json 字符串中得出答案,是否需要循环进行一些验证检查?
    • 如果你能解释一些关于循环的信息,我可以帮助你更好的方法。
    猜你喜欢
    • 2023-03-18
    • 2018-06-15
    • 2022-10-04
    • 1970-01-01
    • 2020-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多