I am looking for the most efficient way to sort a multidimensional array in php.I want to sort the array by the value name
in [result][index][kl][0]
. What is the fastest way to do this? My array has like 100 elements. My array looks like this:
Array
(
[jsonrpc] => 2.0
[id] => req-002
[result] => Array
(
[0] => Array
(
[type] => subst
[lsid] => 11
[date] => 20150209
[startTime] => 955
[endTime] => 1040
[kl] => Array
(
[0] => Array
(
[id] => 29
[name] => S12UB
)
)
)
[1] => Array
(
[type] => subst
[lsid] => 11
[date] => 20150209
[startTime] => 1045
[endTime] => 1130
[kl] => Array
(
[0] => Array
(
[id] => 29
[name] => S12UB
)
)
)
Thank you.
function compareByName($a, $b) {
// the strcmp returns a numeric value above or below 0 depending on the comparison
return strcmp($a['k1'][0]['name'], $b['k1'][0]['name']);
}
Then, assuming your multi-dimensional array is named
$array
, replace the multi-dimensional array $array['result']
with the newly sorted array:$array['result'] = usort($array['result'], 'compareByName');
The documentation for the
usort
and strcmp
should be self-explanatory for understanding how the code works above.
0 comments:
Post a Comment