PHP multi dimensional array sorting by a column with example

By | July 13, 2019
PHP multi dimensional array sorting by a column with example

While working on an application we generally need to sort a multi dimensional array  by a column and sometimes we get frustrate to sort. Because there is no inbuilt function is available to do this operation.

In that case we will need to implement some logic to achieve the desired output.

So here, with this example you can easily achieve the output as a sorted array.

function arraySortByColumn(&$arr, $col, $direction = SORT_ASC) {
   $sort_col = array();
   foreach ($arr as $key=> $row) {
       $sort_col[$key] = $row[$col];
   }

   array_multisort($sort_col, $direction , $arr);
}


$array = [
  0 => [ "name"=>"Abc", "description"=>"ABC Test Description" ],
  1 => [ "name"=>"Bcd", "description"=>"BCD Test Description" ],
  2 => [ "name"=>"Cde", "description"=>"CDE Test Description" ],
  3 => [ "name"=>"Def", "description"=>"DEF Test Description" ],
  4 => [ "name"=>"Efg", "description"=>"EFG Test Description" ]
];
arraySortByColumn($array, 'description');
print_r($array);

In the above piece of code, there is a function named as arraySortByColumn. which performs sorting and give resultant sorted array.

In this function we passed three parameter and third one that is direction, is optional with the default value SORT_ASC. It means if we do not pass direction it will sort in ascending order. We can pass SORT_DESC for descending order sorting..

We pass an array to which we want to sort as first parameter and in the second parameter we pass column name by which sorting would be performed.

And you do not need to assign this function call into a variable  because array passing in the first parameter in pass by reference so the result would be your original array variable.