phparrayssortingmultidimensional-array

Sort single-element rows of a 2d array in a descending direction


var_export($array) of an array gives me this:

array 
    ( 

     0 => array ( 'id_20200514222532' => '4', ), 
     1 => array ( 'id_20200521123813' => '5', ), 
     2 => array ( 'id_20200521125410' => '8', ), 
     3 => array ( 'id_20200523003107' => '3', ), 
     4 => array ( 'id_20200523214047' => '2', ), 

    )

It should be sorted in descending order based on the numbers, so first 8, second 5 and so on...


Solution

  • You can use usort() for this, a sorter function that accepts a callback for comparing two values

    usort($array, function ($a, $b) {
        return reset($b) - reset($a);
    });
    

    That callback function we gave usort() will get two "random" items of the array. I used reset($a) and reset($b) to get the first values out of the child arrays, then I compared them with a simple subtraction.