Friday, 14 November 2014

Sorting multidimensional arrays with single function

<?php
function sortarray($ary, $key = 0) {
  if (!is_array($ary[0]))
    sort($ary);
  else {
    $sorter = array();
    foreach ($ary as $flv)
      $sorter[] = $flv[$key];
       
    array_multisort($sorter, SORT_ASC, $ary);
  }
 
  return($ary);
}
  
 
$ar = array('Yahoo','Google','Bing');
$ar = sortarray($ar);
print_r($ar);
 
$ar = array();
  
$ar[] = array('nick' => 'jojo', 'name' => 'John Shiflett');
$ar[] = array('nick' => 'gogo', 'name' => 'Micheal Gibbins');
$ar[] = array('nick' => 'nono', 'name' => 'Noland Terry');
 
$ar = sortarray($ar,"nick");
 
print_r($ar);
?>

0 comments:

Post a Comment