-1
Array
(
    [data] => Array
        (
            [0] => Array
                (
                    [name] => Nicki Escudero
                    [id] => 27700035
                )

            [1] => Array
                (
                    [name] => Yorgo Nestoridis
                    [id] => 504571368
                )
         )
)

How can I sort this multidimensional array using its name?

I tried with array_multisort but it's not working.

Ry-
  • 199,309
  • 51
  • 404
  • 420
  • 2
    possible duplicate of [Sorting an associative array in PHP](http://stackoverflow.com/questions/777597/sorting-an-associative-array-in-php) – Ry- Dec 17 '11 at 16:04

3 Answers3

0

It is already sorted :-) What do you want to sort by? And where is the data coming from? if you get it from a DB you should sort differently.

Richard
  • 4,038
  • 5
  • 30
  • 50
0

If those are the only two values you have, you can try making id the index of the array and the name can be the value. You can then use asort to sort the array by name and maintain the index-value relation.

By making id the index, I mean $array[27700035] would return Nicki Escudero.

// Copy the array to a new array.
foreach($array as $val) {
    $newArray[$val['id']] = $val['name'];
}

asort($newArray);

Edit: I've gone through the manual and you can also use usort with a custom comparison function. Although I've never used this and can be of very little help... PHP usort

0

If you want to use array_multisort, you would use the following:

$array = array(
    'data' => array(
        array(
            'name' => 'Yorgo Nestoridis',
            'id'   => 504571368,
        ),  
        array(
            'name' => 'Nicki Escudero',
            'id'   => 27700035,
        ),  
    ),  
);  

$names = array();
foreach($array['data'] as $datum) {
    $names[] = $datum['name'];
}   

array_multisort($names, SORT_ASC, $array['data']);
var_dump($array); // now sorted by name

The other choice is to use a custom comparison function:

function compareNames($a, $b) {
    return strcmp($a['name'], $b['name']);
}   

usort($array['data'], 'compareNames');
cmbuckley
  • 33,879
  • 7
  • 69
  • 86