How to sort multidimentional array using php

Suppose you have an multidimentional array like below example and you want to sort that array from any index value 

Lets take an example - I have an array with car name, model and color index like below

 $cars = array
  (
  array('car'=>"Volvo",'model'=>"2014",'color'=>"blue"),
  array('car'=>"BMW",'model'=>"2014",'color'=>"red"),
  array('car'=>"Saab",'model'=>"2012",'color'=>"yellow"),
  array('car'=>"Land Rover",'model'=>"2013",'color'=>"green")
  );
Now i want to sort this array by car name in accending order. Below is a simple function.

function multi_sort($arr, $index) {
    $b = array();
    $c = array();
    foreach ($arr as $key => $value) {
        $b[$key] = $value[$index];
    }
    asort($b);
    foreach ($b as $key => $value) {
        $c[] = $arr[$key];
    }
    return $c;
}


In the above function you just need to pass two parameter -
  1. Array that you want to sort.
  2. Index from which value you want to sort.

Method of using -

$cars=multi_sort($cars, 'car');

echo "<pre>";

print_r($cars);die;

Output :

Array
(
    [0] => Array
        (
            [car] => BMW
            [model] => 2014
            [color] => red
        )

    [1] => Array
        (
            [car] => Land Rover
            [model] => 2013
            [color] => green
        )

    [2] => Array
        (
            [car] => Saab
            [model] => 2012
            [color] => yellow
        )

    [3] => Array
        (
            [car] => Volvo
            [model] => 2014
            [color] => blue
        )

)
 
 
If you like this post don't forgot to leave comment 
 
Happy coding :)
Chears  

Post a Comment

Previous Post Next Post