给阵列“A”排序数组`B`,同时保持一些元素不变

时间:2013-05-16 17:26:36

标签: php arrays sorting

我有一个数组A,用作排序数组B的基础,但是,如果元素不存在,我想保留B中元素的位置在数组A

$A = array (
  0 => 'Peter',
  1 => 'John',
  2 => 'Mike',
  3 => 'Josh',
  4 => 'Bob',
  5 => 'Jan'
);

$B = array (
   0 => array ('name' => 'Aaron'),
   1 => array ('name' => 'Adam'),
   2 => array ('name' => 'Bob'),
   3 => array ('name' => 'Jan'),
   4 => array ('name' => 'John'),
   5 => array ('name' => 'Matt'),
   6 => array ('name' => 'Mike'),
   7 => array ('name' => 'Peter'),
);

所以B会根据A

对其进行排序
$B = array (
   0 => array ('name' => 'Aaron'), // keep position since is not in `A`
   1 => array ('name' => 'Adam'),  // keep position since is not in `A`
   2 => array ('name' => 'Peter'), // move it up since is first pos in `A`
   3 => array ('name' => 'John'),  
   4 => array ('name' => 'Mike'),
   5 => array ('name' => 'Bob'),
   6 => array ('name' => 'Jan'),
   7 => array ('name' => 'Matt'),
);

我该如何对此进行排序?

1 个答案:

答案 0 :(得分:0)

只要您的示例出错并且Matt不想移动它就行了(我只使用$A$B的小写字母:

$b_names = array();
foreach($b as $val) {
    $b_names[] = $val['name'];
}
$a_counter = 0;
foreach($b as $key => $val) {
    if(in_array($val['name'],$a)) {
        while(!in_array($a[$a_counter], $b_names)) {
            $a_counter++;
        }
        $b[$key]['name'] = $a[$a_counter];
        $a_counter++;
    }
}