Wednesday, August 20, 2014

PHP multi dimensional array sorting utility function

PHP has a great collection of array functions. When it comes to sorting a multi dimensional array we have the array_multisort function in PHP.
This particular function helps in sorting multiple arrays as well as sorting a multi dimensional array. Please check the documentation here
When using this function to sort a multi dimensional array, we need to do some manipulation in the array before passing it to the array_multisort function. I have created a utility function which does this manipulation. Please feel free to use this function
1:  function getMultiSortedArray($multiDimenAry, $sortKeyOne, $sortKeyOneOrder = SORT_ASC, $sortKeyTwo = '', $sortKeyTwoOrder = SORT_ASC){  
2:      foreach ($multiDimenAry as $key=>$row){  
3:          $tempOneArry[$key] = $row[$sortKeyOne];  
4:          if( !empty($sortKeyTwo) ){  
5:              $tempTwoAry[$key] = $row[$sortKeyTwo];  
6:          }  
7:      }  
8:      if( !empty($sortKeyTwo) ){  
9:          array_multisort($tempOneArry, $sortKeyOneOrder,$tempTwoAry, $sortKeyTwoOrder, $multiDimenAry);  
10:      }else{  
11:          array_multisort($tempOneArry, $sortKeyOneOrder, $multiDimenAry);  
12:      }  
13:      return $multiDimenAry;  
14:  }  

I would update with a pastebin link with the usage of this function.
Please click here for the usage of the function

No comments: