8

I have a PHP array that looks like this:

Array{
    [0] {
        'id'       => '0',
        'title'    => 'foo',
        'address'  => '123 Somewhere',
    }
    [1] {
        'id'       => '1',
        'title'    => 'bar',
        'address'  => '123 Nowhere',
    }
    [2] {
        'id'       => '2',
        'title'    => 'barfoo',
        'address'  => '123 Elsewhere',
    }
    [3] {
        'id'       => '3',
        'title'    => 'foobar',
        'address'  => '123 Whereabouts',
    }
}

and I want to sort it by the 'title' key in the nested arrays, to look like this:

Array{
    [1] {
        'id'       => '1',
        'title'    => 'bar',
        'address'  => '123 Nowhere',
    }
    [2] {
        'id'       => '2',
        'title'    => 'barfoo',
        'address'  => '123 Elsewhere',
    }
    [0] {
        'id'       => '0',
        'title'    => 'foo',
        'address'  => '123 Somewhere',
    }
    [3] {
        'id'       => '3',
        'title'    => 'foobar',
        'address'  => '123 Whereabouts',
    }
}

The first level key values don't matter since I'm keeping track of each nested array via the nested key 'id'.

I've played with ksort() but with no success.

nobody
  • 19,814
  • 17
  • 56
  • 77
melat0nin
  • 860
  • 1
  • 16
  • 37
  • 1
    possible duplicate of [PHP sort multidimensional array by value](http://stackoverflow.com/questions/2699086/php-sort-multidimensional-array-by-value) – Evan Mulawski Mar 26 '12 at 12:44

1 Answers1

33

You should use usort() (i'm assuming PHP 5.3+ here):

usort($your_array, function ($elem1, $elem2) {
     return strcmp($elem1['title'], $elem2['title']);
});

Edit: I hadn't noticed you wanted to preserve index association, so you actually need to use uasort() instead, with the same parameters.

Edit2: Here is the pre-PHP 5.3 version:

function compareElems($elem1, $elem2) {
    return strcmp($elem1['title'], $elem2['title']);
}

uasort($your_array, "compareElems");
SirDarius
  • 41,440
  • 8
  • 86
  • 100
  • 1
    Perfect, that's exactly what I needed. There are a few alternative solutions on SO but this seems more elegant than most (or all) of them. – melat0nin Mar 26 '12 at 13:48
  • Hmm have just transferred to a server with PHP <5.3, so the embedded function doesn't work.. how would I refactor this to achieve the same effect with the function() outside uasort? – melat0nin Mar 28 '12 at 14:17