我有两个数组:
Array
(
[15407] => Array
(
[id] => 15407
[group] => 9083
[value] => 60.00000
)
[15473] => Array
(
[id] => 15473
[group] => 9109
[value] => -15.000000
)
[15474] => Array
(
[id] => 15474
[group] => 9109
[value] => -20.000000
)
)
Array
(
[15407] => Array
(
[id] => 15407
[group] => 9083
[value_prev] => 100.000000
)
[15474] => Array
(
[id] => 15474
[group] => 9109
[value_prev] => -100.000000
)
)
我试图通过键组合这些数组,如果匹配则添加新元素(value_prev),如果不存在则添加0,所以我需要这些数组:
Array
(
[15407] => Array
(
[id] => 15407
[group] => 9083
[value] => 60.00000
[value_prev] => 100.000000
)
[15473] => Array
(
[id] => 15473
[group] => 9109
[value] => -15.000000
[value_prev] => 0
)
[15474] => Array
(
[id] => 15474
[group] => 9109
[value] => -20.000000
[value_prev] => -100.000000
)
)
我尝试使用array_keys函数,但无法获取所需的数组。 我找到了一些解决方案,但没有帮助我,因为数组的结构不相同。
答案 0 :(得分:2)
由于数组是关联的,所以这是一个非常简单的任务。
循环数组1,并查看键是否存在于数组2中,如果它确实复制了值,则添加0值。
$keys = array_keys($arr2);
foreach($arr1 as $key => &$sub){
if(in_array($key, $keys)){
$sub["value_prev"] = $arr2[$key]["value_prev"];
}else{
$sub["value_prev"] = 0;
}
}