PHP - Sorting a multidimensional array

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.

Answers


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');

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.


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


Need Your Help

slidedown and z-index issue?

jquery css slidedown

this is my site . So , if you press the login link (up - left) you can see sliding down a div . It works, the problem is when i starting to play with ctrl + scroll , everything from the div is star...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.