按值排序JSON值

时间:2016-05-24 06:27:11

标签: php json sorting foreach

这是我的JSON文件:

    {
"example": "1",
"example2": 2,
"text": "3",
"info": {
    "agent": 4,
    "sum": 5,
    "collection": [{
        "Name": "6",
        "Pic": "7"
    }, {
        "Name": "8",
        "Pic": "9"
    }, {
        "Name": "10",
        "Pic": "11"
    }]
     }

      }

我在foreach循环中显示JSON文件的结果:

$data = json_decode(file_get_contents('http://linktojson.com'));
foreach($data->info->collection as $key){

    echo $key->Pic;
    echo $key->Name;

  }

正如您所看到的,' Pic'有不同的数字。如何使用sort()在foreach循环顶部显示最大数字显示,在底部显示最低显示?

1 个答案:

答案 0 :(得分:-1)

您需要在此处使用array_multisortCheck Online

$json = '{
"example": "1",
"example2": 2,
"text": "3",
"info": {
    "agent": 4,
    "sum": 5,
    "collection": [{
        "Name": "6",
        "Pic": "7"
        }, {
            "Name": "8",
            "Pic": "9"
        }, {
            "Name": "10",
            "Pic": "11"
        }]
     }
}';

$result = json_decode ($json, true);
foreach($result  as $key => $value){
    if($key == 'info'){
        $keys = array_keys($value['collection']);
        array_multisort(
            array_column($value['collection'], 'Pic'), SORT_DESC, SORT_NUMERIC, $value['collection'], $keys
        );
        $value = array_combine($keys, $value['collection']);
        foreach($value as $val){
            echo $val['Pic']." - ".$val['Name']."<br/>";
        }
    }   
}

结果:

11 - 10
9 - 8
7 - 6