Tags

, , ,

I find myself with a multidimensional array that I want to sort by a value in a sub-array. I have an array that might look like this:

//an array of some name I like
$name =  array(
'1' => array('name'=>'Vikas'),
'2' => array('name'=>'Avinash'),
'3' => array('name'=>'Nilesh')
);

I want to sort array alphabetically by “name”. PHP provides many functions for sorting arrays, but none will work here like as ksort(), usort()…

So I developed a quick function to sort by the value of a key in a sub-array. Please note this version does a case-insensitive sort. See subval_sort() below.

function subval_sort($a,$subkey) {
   foreach($a as $k=>$v) {
      $b[$k] = strtolower($v[$subkey]);
   }
   asort($b);
   foreach($b as $key=>$val) {
     $c[] = $a[$key];
   }
   return $c;
}

To use it on the above, I would simply type:

$name = subval_sort($name,'name');
print_r($name);

This is what you should expect see:

 Array
(
   [0] => Array
   (
      [name] => Avinash
   )
   [1] => Array
   (
      [name] => Nilesh
   )
   [2] => Array
   (
      [name] => Vikash
   )
)
Advertisements