Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP sort 2d array alphabetically by nested value

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.

like image 984
melat0nin Avatar asked Mar 26 '12 12:03

melat0nin


People also ask

How do I sort a multidimensional array by column in PHP?

array_multisort() can be used to sort several arrays at once, or a multi-dimensional array by one or more dimensions. Associative (string) keys will be maintained, but numeric keys will be re-indexed. Note: If two members compare as equal, they retain their original order.

How do you sort a 2D array?

Make the 2D array into a separate simple (1D) array (STEP 1). Then use the Arrays. sort() method to sort the simple array (STEP 2). Then set each space of the 2D array to be the number of columns across (X-coordinate where the space will be changed) multiplied by the number of spaces per row in the 2D array.

How do I sort a 2D array in PHP?

The array_multisort() function returns a sorted array. You can assign one or more arrays. The function sorts the first array, and the other arrays follow, then, if two or more values are the same, it sorts the next array, and so on.


1 Answers

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");
like image 115
SirDarius Avatar answered Sep 21 '22 13:09

SirDarius