I am coding with PHP and having a multidimensional array. I would like to sort my array. The most important criteria is total points. The second criteria is name.
In other words, the array should be sorted that way:
1st by [info][total], descending
2nd by [info][name], ascending
Array (
[183] => Array (
[3] => Array (
[1] => Array ()
)
[1] => Array (
[8] => Array ()
)
[info] => Array (
[name] => Doe John /* 2nd criteria */
[total] => 4800 /* 1st criteria */
)
)
[380] => Array (
[4] => Array (
[6] => Array ()
)
[info] => Array (
[name] => Davis Ben /* 2nd criteria */
[total] => 14500 /* 1st criteria */
)
[2] => Array (
[5] => Array ()
)
)
)
So, the result should be like this:
Array (
[380] => Array (
[4] => Array (
[6] => Array ()
)
[info] => Array (
[name] => Davis Ben
[total] => 14500
)
[2] => Array (
[5] => Array ()
)
)
[183] => Array (
[3] => Array (
[1] => Array ()
)
[1] => Array (
[8] => Array ()
)
[info] => Array (
[name] => Doe John
[total] => 4800
)
)
)
I have tried this:
foreach ($array as &$item)
{
uasort($item, function ($a, $b)
{
if ($a['total'] == $b['total']
{
return $b['name'] - $a['name'];
}
else
{
return $b['total'] - $a['total'];
}
});
}
I also tried this, but it does not help:
foreach ($array as &$item)
{
uasort($item, function ($a, $b)
{
if ($a['info']['total'] == $b['info']['total'])
{
return $b['info']['name'] - $a['info']['name'];
}
else
{
return $b['info']['total'] - $a['info']['total'];
}
});
}