-1

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

$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'),
);

我怎么能像这样对它进行排序?

4

1 回答 1

0

只要你的例子是错误的,而且马特不应该移动这个作品(我只是用小写字母表示$Aand $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++;
    }
}
于 2013-05-16T17:45:41.233 回答