first Array
(
[category1] => 2
[category2] => 3
[category3] => 1
[category4] => 3
[category5] => 1
)
second Array
(
[q1] => 5
[q2] => 23
[q3] => 3
[q4] => 1
[q5] => 5
)
预期结果,它使用第一个数组中的重复值对第二个数组中的值求和,然后使用第一个数组的唯一值对其进行排序。有人可以给我一些如何实现它的想法吗?
new Array
(
[1] => 8
[2] => 5
[3] => 24
)
答案 0 :(得分:0)
试试:
$array1 = [
'category1' => 2,
'category2' => 3,
'category3' => 1,
'category4' => 3,
'category5' => 1,
];
$array2 = [
'q1' => 5,
'q2' => 23,
'q3' => 3,
'q4' => 1,
'q5' => 5,
];
$output = array_fill_keys(array_unique($array1), 0);
array_map(function($a, $b) use (&$output){ $output[$a] += $b; }, $array1, $array2);
sort($output);
var_dump($output);
输出:
array (size=3)
0 => int 5
1 => int 8
2 => int 24