我有2个阵列:
$array = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4);
$array2 = array(3, 7, 10, 1)
现在我希望我的第一个数组像这样排序(需要第二个数组,因为它包含顺序):
$array = array('c' => 3, 'b' => 2, 'a' => 1, 'd' => 4);
c(10) = first position, b(7) = second position, etc.
我该怎么做?
答案 0 :(得分:0)
是的,你想用另一个数组排序。
<?php
// your arrays
$array = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4);
$array2 = array(3, 7, 10, 1);
//sort using the other array
array_multisort($array2, $array);
//reverse it (as asked)
$result = array_reverse($array, true);
print_r($result);
?>
答案 1 :(得分:0)
试试:
$array = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4);
$array2 = array(3, 7, 10, 1);
$output = array();
array_map(function($key, $data) use (&$output){
$output[$key] = $data;
}, $array2, array_chunk($array, 1, true));
krsort($output);
$output = array_reduce($output, array_merge, array());
var_dump($output);
输出:
array (size=4)
'c' => int 3
'b' => int 2
'a' => int 1
'd' => int 4