我希望你能帮助我...
我有2个数组,我想通过new_date
插入到1array中,如果没有data
,则data
='0',如果没有{{1 }}是data1
='0'。
很抱歉,如果我不知道如何很好地解释它,我举了一个小例子。我已经尝试过array_merge(但是一切都是分开的)和array_combine(它给出了两个参数应该具有相等数量的元素的错误)。 提前谢谢,您可以提供所有帮助...
data1
array1 = array:5 [▼
0 => array:2 [▼
"data" => 118
"new_date" => "06-2017"
]
1 => array:2 [▼
"data" => 263
"new_date" => "07-2017"
]
2 => array:2 [▼
"data" => 264
"new_date" => "08-2017"
]
3 => array:2 [▼
"data" => 266
"new_date" => "09-2017"
]
4 => array:2 [▼
"data" => 306
"new_date" => "10-2017"
]
5 => array:2 [▼
"data" => 100
"new_date" => "11-2017"
]
示例:
array2 = array:6 [▼
0 => array:2 [▼
"data1" => 100
"new_date" => "02-2016"
]
1 => array:2 [▼
"data1" => 170
"new_date" => "06-2017"
]
2 => array:2 [▼
"data1" => 354
"new_date" => "07-2017"
]
3 => array:2 [▼
"data1" => 397
"new_date" => "08-2017"
]
4 => array:2 [▼
"data1" => 421
"new_date" => "09-2017"
]
5 => array:2 [▼
"data1" => 531
"new_date" => "10-2017"
]
答案 0 :(得分:1)
使用array_combine
将new_date
设置为键。然后,将第一个数组元素d1
(在您的示例中为“ data1”)与array_map
相加。好的,在第二个数组上循环并添加d1
存在,其余所有d
(在您的示例中为“ data”)为0的情况。
您可以这样做:
$a1 = array(["d"=>1, "new_date"=> "06-2017"],["d"=>2, "new_date"=> "02-2016"]);
$a2 = array(["d1"=>3, "new_date"=> "06-2017"],["d1"=>4, "new_date"=> "07-2017"]);
$a1 = array_combine(array_column($a1, "new_date"), $a1);
$a2 = array_combine(array_column($a2, "new_date"), $a2);
// adding default d1 as 0
$a1 = array_map(function ($e) {return array_merge($e, ["d1" => 0]);},$a1);
foreach($a2 as $k => $v) {
if (isset($a1[$k]))
$a1[$k]["d1"] = $v["d1"]; // if new_data exist set only d1
else
$a1[$k] = array_merge($v, ["d" => 0]); //add with d as 0
}
您的结果将在$a1