现在我的数组看起来像这样
Array([0] => array([region]=>1[district]=>2[sell]=>3)
[1] => array([region]=>1[district]=>3[sell]=>6)
[2] => array([region]=>1[district]=>4[sell]=>9)
)
我有一个像这样的其他数组
Array([0] => array([buy]=>3)
[1] => array([buy]=>4)
[2] => array([buy]=>5)
)
所以问题是我如何组合两个数组使它看起来像这样? 或者有没有方法将第二个数组推入第一个数组?
Array([0] => array([region]=>1[district]=>2[sell]=>3[buy]=>3)
[1] => array([region]=>1[district]=>3[sell]=>6[buy]=>4)
[2] => array([region]=>1[district]=>3[sell]=>9[buy]=>5)
)
答案 0 :(得分:1)
不要忘记函数式编程。
$existing = [
['a' => 1, 'b' => 2, 'c' => 3],
['a' => 4, 'b' => 5, 'c' => 6],
['a' => 5, 'b' => 8, 'c' => 9],
];
$newItems = [
['d' => 3],
['d' => 4],
['d' => 5]
];
// let's run over those arrays and do array_merge over items
$result = array_map('array_merge', $existing, $newItems);
var_dump($result);
P.S。使用array_replace_recursive
存在更简单的方法$result2 = array_replace_recursive($existing, $newItems);
答案 1 :(得分:0)
试试这个
$existing = array(
0 => array('region'=>1, 'district'=>2, 'sell'=>3),
1 => array('region'=>4, 'district'=>5, 'sell'=>6),
2 => array('region'=>5, 'district'=>8, 'sell'=>9),
);
$newItems = array(
0 => array('buy'=>3),
1 => array('buy'=>4),
2 => array('buy'=>5)
);
foreach($newItems as $i => $data){
$key = array_pop(array_keys($data));
$value = array_pop(array_values($data));
$existing[$i][$key] = $value;
}
echo '<pre>'; print_r($existing); echo '</pre>';