Search code examples
phpsortingindexingassociationsasort

sorting an array with unknown keys and and maintain index association in php


i have an array with the values of statistics taken from 2 executions and their difference. the name of the statistic is the key and it is unknown to me. I want to maintain index association

it is like this

$array["statistic_name_1"][0] = 5
$array["statistic_name_1"][1] = 4
$array["statistic_name_1"][2] = 1   

$array["statistic_name_2"][0] = 10
$array["statistic_name_2"][1] = 4
$array["statistic_name_2"][2] = 6

$array["statistic_name_3"][0] = 15
$array["statistic_name_3"][1] = 10
$array["statistic_name_3"][2] = 5

...

and I want to sort it descending numerically according to the difference of the executions (which is the [key][2])

i have tried asort but i cant find a way to tell it to sort according to the difference


Solution

  • Try something like this:

    function cmp($a, $b)
    {
        return $b[2] - $a[2]
    }
    
    uasort($array, "cmp");
    

    http://www.php.net/manual/en/function.uasort.php

    To put it all on one line you can do:

    uasort($array, function($a, $b){ return $b[2] - $a[2] });