Search code examples
phparrayssorting

Sort an array of arrays by a column value in a descending direction


I've got an array of arrays like this :

Array(
    [id1] => Array (
           /* details */
           [unique] => 3
          )
    [id2] => Array (
           /* details */
           [unique] => 5
    [id3] => Array (
           /* details */
           [unique] => 1
    )
)

Question : How could I sort it by the unique field, so that it is converted like the one following?

Array(
    [id2] => Array (
           /* details */
           [unique] => 5
          )
    [id1] => Array (
           /* details */
           [unique] => 3
    [id3] => Array (
           /* details */
           [unique] => 1
    )
)

Solution

  • Classical task for usort function:

    <?php
    $data = array(
        "id1" => Array (
            "unique" => 3
            ),
        "id2" => Array (
            "unique" => 5),
        "id3" => Array (
            "unique" => 1
            ),
        );
    
    function cmp($a, $b)
    // {{{
    {
        if ($a["unique"] == $b["unique"]) {
            return 0;
        }
        return ($a["unique"] < $b["unique"]) ? 1 : -1;
    }
    // }}}
    
    usort($data, "cmp");
    var_dump($data);
    

    Prints:

    array(3) {
      [0]=>
      array(1) {
        ["unique"]=>
        int(5)
      }
      [1]=>
      array(1) {
        ["unique"]=>
        int(3)
      }
      [2]=>
      array(1) {
        ["unique"]=>
        int(1)
      }
    }
    

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