这是First Array:
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个月
我看过建议的排序数组技术,但没有帮助
答案 0 :(得分:2)
我知道你已经有了答案,但由于你的目标与几个月有关,我想提出这个问题:
Vary
我只是迭代接下来12个月的数字表示并从那里构建数组 - 优先考虑来自for ($i = 1; $i <= 12; $i++) {
$month = date('n', strtotime($i . ' month'));
$merged[$month] = isset($array1[$month]) ? $array1[$month] : $array2[$month];
}
的值。如果$array1
仅用于数组键并且始终充满默认值(0s),则您甚至不需要它,您可能会执行以下操作:
$array2
答案 1 :(得分:2)
无需循环数组。只需一个简单的衬垫即可。
$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的值。
答案 2 :(得分:1)
点击此处查看工作演示:https://eval.in/856000
<?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
)
答案 3 :(得分:1)
根据您提供的当前输入数组,最简单的解决方案如下:
通过保留键来反转第二个数组。 Read more about array_reverse here
将反转数组替换为要替换其键值的第一个输入数组。Read more about array_replace here
$reversedArray = array_reverse($b,1);
$result = array_replace($reversedArray,$a);
echo "<pre>"; print_r($result);