sort a multi-dimensional associative array?

11,986

Solution 1

StackOverflow has lots of similar questions, but let me give you a quick example. For this, you can use the usort() function.

PHP 5.3 example (not the nicest one, but might be easier to understand):

uasort($array, function ($i, $j) {
    $a = $i['lastName'];
    $b = $j['lastName'];
    if ($a == $b) return 0;
    elseif ($a > $b) return 1;
    else return -1;
});

Solution 2

Short and reusable method:

usort($array, 'nameSort');

function nameSort($a, $b)
{
    return strcmp($a['lastName'], $b['lastName']);
}

Solution 3

AS I posted in php.net, you can use this function:

<?php

function sksort(&$array, $subkey="id", $sort_ascending=false) {

    if (count($array))
        $temp_array[key($array)] = array_shift($array);

    foreach($array as $key => $val){
        $offset = 0;
        $found = false;
        foreach($temp_array as $tmp_key => $tmp_val)
        {
            if(!$found and strtolower($val[$subkey]) > strtolower($tmp_val[$subkey]))
            {
                $temp_array = array_merge(    (array)array_slice($temp_array,0,$offset),
                                            array($key => $val),
                                            array_slice($temp_array,$offset)
                                          );
                $found = true;
            }
            $offset++;
        }
        if(!$found) $temp_array = array_merge($temp_array, array($key => $val));
    }

    if ($sort_ascending) $array = array_reverse($temp_array);

    else $array = $temp_array;
}

?>
Share:
11,986
nkcmr
Author by

nkcmr

Updated on June 22, 2022

Comments

  • nkcmr
    nkcmr almost 2 years

    Okay, I have an array that is used to transport names, it looks like this:

    array(2) {
      [0]=>
      array(3) {
        ["firstName"]=>
        string(3) "Joe"
        ["lastName"]=>
        string(5) "Black"
        ["uid"]=>
        int(3225)
      }
      [1]=>
      array(3) {
        ["firstName"]=>
        string(4) "John"
        ["lastName"]=>
        string(3) "Doe"
        ["uid"]=>
        int(3516)
      }
    }
    

    Now, how do I sort this array by lastName?