这是第一个数组:
Array
(
[6] => 1
[8] => 1
[9] => 5
)
第二个数组:
Array
(
[9] => 0
[8] => 0
[7] => 0
[6] => 0
[5] => 0
[4] => 0
[3] => 0
[2] => 0
[1] => 0
[12] => 0
[11] => 0
[10] => 0
)
所需的输出数组:
Array
(
[10] => 0
[11] => 0
[12] => 0
[1] => 0
[2] => 0
[3] => 0
[4] => 0
[5] => 0
[6] => 1
[7] => 0
[8] => 1
[9] => 5
)
我只想对数组进行反向排序,但使用第一个数组值。我已经尝试过
array_reverse
但它只是反向短路数组并且放错了它的值。
注意:所需的数组键是前 12 个月我查看了建议的排序数组技术,但没有帮助
<?php
$array1 = array(6 => 1,
8 => 1,
9 => 5);
$array2 = array(9 => 0,
8 => 0,
7 => 0,
6 => 0,
5 => 0,
4 => 0,
3 => 0,
2 => 0,
1 => 0,
12 => 0,
11 => 0,
10 => 0);
$mergedArray =[];
foreach ($array2 as $key => $value) {
if (array_key_exists($key, $array1)) {
if ($array1[$key] > $array2[$key]) {
$mergedArray[$key] = $array1[$key];
}
else {
$mergedArray[$key] = $array2[$key];
}
}
else {
$mergedArray[$key] = $array2[$key];
}
}
print_r(array_reverse($mergedArray,true));
?>
输出:
Array
(
[10] => 0
[11] => 0
[12] => 0
[1] => 0
[2] => 0
[3] => 0
[4] => 0
[5] => 0
[6] => 1
[7] => 0
[8] => 1
[9] => 5
)
for ($i = 1; $i <= 12; $i++) {
$month = date('n', strtotime($i . ' month'));
$merged[$month] = isset($array1[$month]) ? $array1[$month] : $array2[$month];
}
我只是迭代接下来 12 个月的数字表示,并从那里构建数组 - 优先考虑来自
$array1
的值。 如果
$array2
仅用于数组键并且始终充满默认值(0),则您甚至不需要它,您可以执行以下操作:
for ($i = 1; $i <= 12; $i++) {
$month = date('n', strtotime($i . ' month'));
$merged[$month] = isset($array1[$month]) ? $array1[$month] : 0;
}
$array1 = array(6 => 1,
8 => 1,
9 => 5);
$array2 = array(9 => 0,
8 => 0,
7 => 0,
6 => 0,
5 => 0,
4 => 0,
3 => 0,
2 => 0,
1 => 0,
12 => 0,
11 => 0,
10 => 0);
$res = array_reverse(array_replace($array2, $array1),true);
Var_dump($res);
Array_replace 将替换 array2 中 array1 中的值。