How to sort multidimensional array in PHP

How to sort multidimensional array in PHP

Hello everyone welcome to PHP tutorial. Today I’m going to show you how to sort multidimensional array in PHP . I’m writing this tutorial based on my freelancing project. Story was that, last day i was faced a big problem while I was trying to sort country list and their prices. My friend as well as client Bas Bhan Dar Wals ask me to sort them according to their name. It seems little bit difficult for me when i was started it. Because, some country contains 6 Euro for shipping and others 8 Euro for shipping. So, I was little bit tensed about this problem.

Finally I’d solved this problem . What I’d did with sorting problem, I was just add all country lists in one array and I’d chosse a 3 dimensional array. In first index I’d set order of country , second index contained name of country and last one contained shipping price. Then pass this array as a parameter through my sorting function and I’d got a sorted country lists. This function return an array. I was feeling good when I was completed it successfully. Then I thought, I need to share it with my developer friends. That’s why today I’m writing this tutotrial. Let’s check out my scripts.

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 sorting 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;
}

I’ve create a function called sort_country_lists which have 2 parameters. first one contained array and second one for sorting key. Means which index you want to sort.

Call the funtion and Pass parameters:

// 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');

Output:

sorting multidimensional array

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!

Advertisement

Tags:  

Share It

Related Posts