How to sort multidimensional array in PHP

How to sort multidimensional array in PHP

Today, I will show how to sort a multidimensional array on PHP, and I am writing this tutorial based on one of my freelancing project experiences. 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 a 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 the name of the country and the second one contained the shipping price. Here is the complete PHP code with an 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 is named sort_country_lists, and it requires two parameters. The first must be an array, and the second is the sorting key. Here is an 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');

Was this information helpful? What other tips would you like to read about in the future? Share your comments, feedback, and experiences with us by commenting below!

Total 0 Votes
0

Tell us how can we improve this post?

+ = Verify Human or Spambot ?

Leave a Comment

Back To Top