phparrayssortingmultidimensional-array

Sort a 2D array by a column


Here is my current code to add to the array:

foreach ($query->result() as $exp) {
    $activities[] = array('type' => 'level', 'exp' => $exp->exp, 'timestamp' => $badge->timestamp);
}

How would I go about sorting this array according to the value of the 'timestamp' key?


Solution

  • You would need to use usort which will let you sort the array using a user-defined function.

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

    Example:

    <?php
    function cmp($a, $b)
    {
        if ($a == $b) {
            return 0;
        }
        return ($a < $b) ? -1 : 1;
    }
    
    $a = array(3, 2, 5, 6, 1);
    
    usort($a, "cmp");