我有两个数组需要根据一个特定值反映相同的顺序。我的第一个数组$array1
是一系列整数,我需要$array2
中的辅助数组,它们具有相同的整数值(以及我剩下的一大堆其他数据)为简洁起见,请重新排序以反映$array1
中整数的顺序。
目前我有:
$array1 = array(
[0] => 19,
[1] => 15,
[2] => 18,
[3] => 20
);
$array2 = array (
[0] => array (
[0] => 20,
[1] => 'Some other data.'
),
[1] => array (
[0] => 18,
[1] => 'Some other data.'
),
[2] => array (
[0] => 19,
[1] => 'Some other data.'
),
[3] => array (
[0] => 15,
[1] => 'Some other data.'
)
);
期望排序$array2
:
$array2 = array (
[0] => array (
[0] => 19,
[1] => 'Some other data.'
),
[1] => array (
[0] => 15,
[1] => 'Some other data.'
),
[2] => array (
[0] => 18,
[1] => 'Some other data.'
),
[3] => array (
[0] => 20,
[1] => 'Some other data.'
)
)
答案 0 :(得分:0)
在这种情况下,您应该使用uasort()
function cmp($a, $b) {
$posA = array_search($a[0], $array1);
$posB = array_search($b[0], $array1);
if ($posA == $posB) {
return 0;
}
return ($posA < $posB) ? -1 : 1;
}
uasort($array2, 'cmp');
但它会很慢......
答案 1 :(得分:0)
// make order in form "what => place"
$flip = array_flip($array1);
$new = array();
foreach($array2 as $key=>$item) {
$i = $item[0];
$new[$flip[$i]] = $item;
}