Sort a multidimensional array by deep value

I have a set of data containing latency information that I want to sort by the “latency_ms” value in this array of arrays:

{ "myserver.local-192.168.1.1": { "alias":"myhost", "unavailable":0, "latency_ms":33 }, "myserver.local-192.168.2.2": { "alias":"anotherhost", "unavailable":0, "latency_ms":38 }, "servertwo.local-192.168.3.3": { "alias":"athirdhost", "unavailable":0, "latency_ms":26 } }

I’ve tried multiple ways of manipulating uasort() and array_multisort(), but I can’t seem to wrap my head around what I’m doing wrong. This object needs to have the member arrays ordered by their respective latency_ms values, in descending order. Can anyone help me out?

For reference, this is as close as I’ve gotten (it sorts latency_ms correctly, but the entire list is sorted by the top-level key first, and THEN latency_ms, which is not what I want):

foreach($rtt_data as $ip){ foreach($ip as $key=>$value){ if(!isset($sortArray[$key])){ $sortArray[$key] = array(); } $sortArray[$key][] = $value; } } $orderby = "latency_ms"; if (is_array($sortArray[$orderby])){ array_multisort($sortArray[$orderby],SORT_DESC,$rtt_data); }

Thanks in advance!!!

You can use usort, this order an array by a function defined by user,
this function receives 2 item of array and return 0 if are equal, -1 if first are lower than second and 1 if second are lower than first.
[php]

function cmp($a, $b)
{
if ($a[‘latency_ms’] == $b[‘latency_ms’) {
return 0;
}
return ($a[‘latency_ms’] < $b[‘latency_ms’]) ? -1 : 1;
}

usort($rtt_data, “cmp”);[/php]

Sponsor our Newsletter | Privacy Policy | Terms of Service