这是我的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循环顶部显示最大数字显示,在底部显示最低显示?
答案 0 :(得分:-1)
您需要在此处使用array_multisort
。 Check 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