按照另一个数组的顺序对多维数组进行排序

时间:2010-06-23 20:03:39

标签: php sorting arrays

考虑以下数组:

$main_array = array();
$main_array[0] = array('location'=> array('France', 'Germany'), 'random_number'=> array('6520'));
$main_array[1] = array('location'=> array('Italy', 'Switzerland'), 'random_number'=> array('3245'));
$main_array[2] = array('location'=> array('Portugal', 'Spain'), 'random_number'=> array('9981'));
$main_array[3] = array('location'=> array('Turkey', 'Greece'), 'random_number'=> array('1098'));

我想根据random_number[0]键的值并基于以下数组的序列对此数组进行排序:

$sequenced = array('3245','1098','6520','9981');

所以最终排序的数组看起来像:

$final_array = array();
$final_array[0] = array('location'=> array('Italy', 'Switzerland'), 'random_number'=> array('3245'));
$final_array[1] = array('location'=> array('Turkey', 'Greece'), 'random_number'=> array('1098'));
$final_array[2] = array('location'=> array('France', 'Germany'), 'random_number'=> array('6520'));
$final_array[3] = array('location'=> array('Portugal', 'Spain'), 'random_number'=> array('9981'));

知道如何实现这一目标吗?

1 个答案:

答案 0 :(得分:2)

function sorter($array, $sequence){
  $tmp = array();
  foreach($sequence as $s){
    foreach($array as $a){
      if($a[random_number][0] == $s){ 
        array_push($tmp, $a);
        break;
      }   
    }   
  }
  return $tmp;
}

$final_array = sorter($main_array, $sequenced);