How to Sort Multi-dimensional Array by Key Value in PHP

The order of an array elements can sort by key using foreach() loop, but it will be a complicated process, and execution time is high. PHP array_multisort() function provides an easy way to sort a multidimensional array by key value. In this example code snippet, we will show you how to sort the order of multi-dimensional array elements by key in PHP.

The following code helps to sort multi-dimensional arrays by key in PHP.

  • Use PHP array_column() function to get values from a specifc key column in array.
  • Use PHP array_multisort() function to sort an array by key value.

In this example code snippet, the first_name key is specified to sort the $records array in ascending order.

$records = array( 
  array(
    
'first_name' => 'John',
    
'last_name' => 'Doe',
    
'email' => 'john.doe@gmail.com'
  
),
  array(
    
'first_name' => 'Gary',
    
'last_name' => 'Riley',
    
'email' => 'gary@hotmail.com'
  
),
  array(
    
'first_name' => 'Edward',
    
'last_name' => 'Siu',
    
'email' => 'siu.edward@gmail.com'
  
),
  array(
    
'first_name' => 'Betty',
    
'last_name' => 'Simons',
    
'email' => 'simons@example.com'
  
)
);

$key_values array_column($records'first_name');
array_multisort($key_valuesSORT_ASC$records);

After sorting, the $records array is returned in the following order.

Array
(
    [0] => Array
        (
            [first_name] => Betty
            [last_name] => Simons
            [email] => simons@example.com
        )

    [1] => Array
        (
            [first_name] => Edward
            [last_name] => Siu
            [email] => siu.edward@gmail.com
        )

    [2] => Array
        (
            [first_name] => Gary
            [last_name] => Riley
            [email] => gary@hotmail.com
        )

    [3] => Array
        (
            [first_name] => John
            [last_name] => Doe
            [email] => john.doe@gmail.com
        )

)

2 Comments

  1. Alexa Said...
  2. Jack Said...

Leave a reply

keyboard_double_arrow_up