The order of an array value can sort by key using foreach () loop, but it will be a complicated method, and execution time is long. PHP array_multisort () function provides us an easy way to sort a multidimensional array by key value. In this code snippet, we will do how to sort, arrange multi-dimensional array elements by key in PHP.
The following code snippet helps to sort multi-dimensional arrays by key in PHP.
Use PHP array_column () function to get values from a specific key column the array.
Use array_multisort() php function to sort an array by key value.
In this code snippet, the first_name key is defined 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_values, SORT_ASC, $records);
After sorting arrays, 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
)
)
Have Fun!
0 Comments