The Codesee The Codesee - 6 months ago 12
PHP Question

Sort multiple arrays from highest to lowest

I'm displaying data from multiple

JSON
files using an
array
and using
sort();
to sort the values of
ID
from highest to lowest.

The problem I'm facing is that
sort();
is ordering both arrays separately, causing the following will be outputted:


  • 11

  • 9

  • 7

  • 56

  • 12

  • 5



11, 9 and 7 (the first array) are sorted and 56, 12 and 5 (the second array) are sorted. How do I merge the arrays so that the following is outputted:


  • 56

  • 12

  • 11

  • 9

  • 7

  • 5



Here's my JSON array:

$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 and sort it:

foreach ($homepage as $homepage2) {
$data = json_decode($homepage2, false);

usort($data->info->collection, function ($a, $b) {
return $b->ID - $a->ID;
});


Here's where I finally display it:

foreach($data->info->collection as $key) {
echo'
'.$key->ID.'
';
}
}

Answer

First you need to decode those jsons to arrays and add them to for example $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...

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.

Comments