[英]Sort multiple arrays from highest to lowest
I'm displaying data from multiple JSON
files using an array
and using sort();
我正在使用
array
并使用sort();
显示来自多个JSON
文件的数据sort();
to sort the values of ID
from highest to lowest. 将
ID
的值从最高到最低排序。
The problem I'm facing is that sort();
我面临的问题是
sort();
is ordering both arrays separately, causing the following will be outputted: 分别对两个数组进行排序,导致输出以下内容:
11, 9 and 7 (the first array ) are sorted and 56, 12 and 5 (the second array) are sorted. 对11,9和7 (第一阵列 )进行排序,并对56,12和5 (第二阵列)进行排序。 How do I merge the arrays so that the following is outputted:
如何合并数组以便输出以下内容:
Here's my JSON array: 这是我的JSON数组:
$homepage = array();
$homepage[] = '{
"info": {
"collection": [
{
"ID": "7"
},
{
"ID": "9"
},
{
"ID": "11"
}
]
}
}';
$homepage[] = '{
"info": {
"collection": [
{
"ID": "12"
},
{
"ID": "56"
},
{
"ID": "5"
}
]
}
}';
Here's where I decode the JSON array, sort it and echo it: 这是我解码JSON数组,对其进行排序并回显它的地方:
foreach ($homepage as $homepage2) {
$data = json_decode($homepage2, false);
usort($data->info->collection, function ($a, $b) {
return $b->ID - $a->ID;
});
foreach($data->info->collection as $key) {
echo'
'.$key->ID.'
';
}
}
First you need to decode those jsons to arrays and add them to for example $homepage_decoded
... 首先,您需要将这些jsons解码为数组并将其添加到例如
$homepage_decoded
...
$homepage_decoded = array();
foreach($homepage as $hp)
$homepage_decoded[] = json_decode($hp,true);
$merged = array_unique(call_user_func_array('array_merge', $merged));
And then sort $merged
... 然后排序
$merged
...
sort($merged,SORT_NUMERIC);
Excuse me if there is some syntax error in code I given, writting it from phone. 如果我给出的代码中有一些语法错误,请从手机写入,请原谅。 But idea should be clear.
但想法应该清楚。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.