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.
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_values, SORT_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
)
)
Thank you!!
THANK YOU!!!! After a day of trying to figure this out.. you explanation did the job.
Awesome!