Today I am going to show how to sort a multidimensional array on PHP and I am writing this tutorial based one of my freelancing project experience. So, I was working on a client project and resolving a major issue. The client asked to sort the array based on the country name. But, the country name was the “key” of an nested array.
To fix that issue, I decided to create a custom function. Add all the countries in an array ( 3 dimensional array). Inside the nested array the first index contained name of country and second one contained the shipping price. Here goes the full PHP code with example.
First Create a three dimensional array:
//Declare an array. $shipping_country_lists = array( '1' => array('country'=>'Australia', 'price'=>'8.00'), '2' => array('country'=>'Brazil', 'price'=>'8.00'), '3' => array('country'=>'Israel', 'price' =>'8.00'), '4' => array('country'=>'Japan', 'price'=>'8.00'), '5' => array('country'=>'New Zealand', 'price' =>'8.00'), '6' => array('country'=>'United States', 'price'=>'8.00'), '7' => array('country'=>'Canada', 'price' =>'8.00'), '8' => array('country'=>'Argentina', 'price'=>'8.00'), '9' => array('country'=>'Chile', 'price' =>'8.00'), '10' => array('country'=>'Russia', 'price' =>'8.00') );
Write A Custom Function:
// Now declare a function that sort multidimensional array depends on key. function sort_country_lists($a,$subkey) { foreach($a as $k=>$v) { $b[$k] = strtolower($v[$subkey]); } asort($b); foreach($b as $key=>$val) { $c[] = $a[$key]; } return $c; }
Alright, now it’s time to call the function. The custom function named as sort_country_lists and it requires two parameters. First one must be an array and second one is the sorting key. Here goes the example of that function call.
Call the custom function:
// Call the function and pass parameters. // In first parameter you need to pass multidimensional array and in second on // You need to pass key. Here key is 'country'. sort_country_lists($country_lists,'country');
Video Tutorial:
Was this information useful? What other tips would you like to read about in the future? Share your comments, feedback and experiences with us by commenting below!