Thursday, September 6, 2012

Sorting Multidimensional array in php

This function helps you to sort multidimensional array based on an particular index in that array

sortmulti($resArray,'INDEXNAME','asc',true,true);

Parameter 1 : It is the multidimensional array.
Parameter 2 : It is the index name in multidimensional array.
Parameter 3 : It is to define the ascending or descending order of index name multidimensional array.Acceptable values(asc,desc).
Parameter 4 : If the index has alphsnumeric values then set this as true else false.
Parameter 5 : If you want index name to case sensistive set this as true.

function sortmulti ($array, $index, $order, $natsort=FALSE, $case_sensitive=FALSE) {
  if(is_array($array) && count($array)>0) {
    foreach(array_keys($array) as $key)
      $temp[$key]=$array[$key][$index];
    if(!$natsort) {
      if ($order=='asc')
      asort($temp);
      else
      arsort($temp);
    }
    else
    {
      if ($case_sensitive===true)
        natsort($temp);
       else
        natcasesort($temp);
      if($order!='asc')
        $temp=array_reverse($temp,TRUE);
    }
    foreach(array_keys($temp) as $key){
      if (is_numeric($key))
        $sorted[]=$array[$key];
      else
        $sorted[$key]=$array[$key];
    }
    return $sorted;
   }
  return $sorted;
}

1 comment: