我有一个数组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'),
);
我该如何对此进行排序?
答案 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++;
}
}