Sorting a multidimensional array in PHP


If it becomes necessary to sort a multidimensional array by some value by the right key in PHP, the usual array sorting function will not work for this case. For such cases, PHP has a usort function that allows you to use a user-defined function to sort a multidimensional array as we want.

As an example, there is such an array:
$multiplearray[‘key’][‘color’]  => ‘red’;
$multiplearray[‘key’][‘order’] => ‘5’;

$multiplearray[‘key’][‘color’]  => ‘black’;
$multiplearray[‘key’][‘order’] => ‘3’;

$multiplearray[‘key’][‘color’]  => ‘white’;
$multiplearray[‘key’][‘order’] => ‘2’;

$multiplearray[‘key’][‘color’]  => ‘green’;
$multiplearray[‘key’][‘order’] => ‘4’;

$multiplearray[‘key’][‘color’]  => ‘grey’;
$multiplearray[‘key’][‘order’] => ‘1’;

You need to sort the array by value, which are in the key “order”. To do this, use the code below

<?php
function build_sorter($key){ /* Algorithm for sort array. */
	return function($a, $b) use ($key){
		return strnatcmp($a[$key], $b[$key]); /* We use PHP strnatcmp function for more accurate comparison of values */
	}
}

usort($multiplearray['key'], build_sorter('order')); /* PHP sorting function with created algorithm */
?>

As a result, after applying the function + sorting algorithm, we get the following array:
$multiplearray[‘key’][‘color’]  => ‘grey’;
$multiplearray[‘key’][‘order’] => ‘1’;

$multiplearray[‘key’][‘color’]  => ‘white’;
$multiplearray[‘key’][‘order’] => ‘2’;

$multiplearray[‘key’][‘color’]  => ‘black’;
$multiplearray[‘key’][‘order’] => ‘3’;

$multiplearray[‘key’][‘color’]  => ‘green’;
$multiplearray[‘key’][‘order’] => ‘4’;

$multiplearray[‘key’][‘color’]  => ‘red’;
$multiplearray[‘key’][‘order’] => ‘5’;




Connect

If you have any questions, want to get individual advice or you have an interesting offer, you can contact via the feedback form.

Or write to the email info@bobreod.ru





By submitting the form, you agree to our privacy policy