Home » Php » sort multidimensional array by key value in php

sort multidimensional array by key value in php

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have a multidimensional array, assume this array :

$my_array = array(
    'index1' => array(
        'order' => 4,
        'other_key1' => 'other_value1',
        'other_key2' => array(..),
        ...
    ),
    'index2' => array(
        'order' => 3,
        'other_key3' => 'other_value3',
        'other_key4' => array(..),
        ...
    ),
    'index3' => array(
        'order' => 5,
        'other_key5' => 'other_value5',
        'other_key6' => array(..),
        ...
    ),
    'index4' => array(
        'order' => 7,
        'other_key7' => 'other_value7',
        'other_key7' => array(..),
        ...
    ),
);

I want sort $my_array by order key, can you help me?
please suggest your solution. thanks

How to&Answers:
function sortByOrder( $a, $b ) {
  return $a['order'] - $b['order'];
}

uasort($my_array, 'sortByOrder' );

I think thats it.