Monday, 27 August 2018

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.

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

0 comments:

Post a Comment