将一个数组与另一个多维数组进行比较时遇到问题。
我想将数组A
与B
进行比较,并检查数组B中缺少数组A中的哪些日期(值)。
在缺少日期的地方,我想在数组A中插入带有“日期值”的“日期”键,以及键“counter”=> 0
$A = [
0 => "2018-03",
1 => "2018-02",
2 => "2018-01",
3 => "2017-12",
4 => "2017-11",
5 => "2017-10"
];
$B = [
0 => [
'logins' => [
0 => [
"date" => "2018-03",
"counter" => "65"
],
1 => [
"date" => "2018-02",
"counter" => "40"
],
2 => [
"date" => "2017-12",
"counter" => "77"
]
]
],
1 => [
'logins' => [
0 => [
"date" => "2018-02",
"counter" => "44"
],
1 => [
"date" => "2018-01",
"counter" => "24"
]
]
]
];
结果数组C
应如下所示:
$C = [
[
'logins' => [
['date' => '2018-03', 'counter' => 65],
['date' => '2018-02', 'counter' => 40],
['date' => '2018-01', 'counter' => 0],
['date' => '2017-12', 'counter' => 77],
['date' => '2017-11', 'counter' => 0],
['date' => '2017-10', 'counter' => 0],
],
],
[
'logins' => [
['date' => '2018-03', 'counter' => 0],
['date' => '2018-02', 'counter' => 44],
['date' => '2018-01', 'counter' => 24],
['date' => '2017-12', 'counter' => 0],
['date' => '2017-11', 'counter' => 0],
['date' => '2017-10', 'counter' => 0],
],
]
];
答案 0 :(得分:0)
循环$B
然后在$A
上的每个项目循环上,检查是否找到了日期,如果没有,则添加它,然后按$A
对数组进行排序。
<?php
foreach ($B as &$row) {
foreach ($A as $date) {
if (!in_array($date, array_column($row['logins'], 'date'))) {
$row['logins'][] = [
"date" => $date,
"counter" => 0
];
}
}
array_multisort($row['logins'], SORT_DESC, $A);
}
print_r($B);
<强>结果:强>
Array
(
[0] => Array
(
[logins] => Array
(
[0] => Array
(
[date] => 2018-03
[counter] => 65
)
[1] => Array
(
[date] => 2018-02
[counter] => 40
)
[2] => Array
(
[date] => 2018-01
[counter] => 0
)
[3] => Array
(
[date] => 2017-12
[counter] => 77
)
[4] => Array
(
[date] => 2017-11
[counter] => 0
)
[5] => Array
(
[date] => 2017-10
[counter] => 0
)
)
)
[1] => Array
(
[logins] => Array
(
[0] => Array
(
[date] => 2018-03
[counter] => 0
)
[1] => Array
(
[date] => 2018-02
[counter] => 44
)
[2] => Array
(
[date] => 2018-01
[counter] => 24
)
[3] => Array
(
[date] => 2017-12
[counter] => 0
)
[4] => Array
(
[date] => 2017-11
[counter] => 0
)
[5] => Array
(
[date] => 2017-10
[counter] => 0
)
)
)
)