Merge two arrays by key but mantain the key of the first in PHP, array_combine fails
I am trying to combine two arrays but mantaining the key of the first.
I've this data:
$days = array(
1 => array("name" => "Monday"),
2 => array("name" => "Tuesday"),
3 => ...
30 => array("name" => "Sunday"),
);
And another one with the clicks:
$clics = array(
2 => array("clicks" => 4),
10 => array("clicks" => 2),
);
My desired array is:
$final = array(
1 => array("name" => "Monday"),
2 => array("name" => "Tuesday", "clicks" => 4),
3 => ...
4 =>
5 =>
...
10 => array("name" => "Tuesday", "clicks" => 2),
..
30 => array("name" => "Sunday"),
);
In the second array if there is no click the index开发者_运维知识库 doesn't exists. I have tried array_combine but needs to have the same key and array_merge fails to.
What option I have?
Thank you in advance
Take a look at the array_merge_recursive function on PHP.net. Also, check out the comments there to seek if one of those functions are providing the desired array (I.E. comment #104145 and comment #102379
Also, please note that with the use of a foreach, you are sure to have the desired array eventually. Are there any specific reasons why you don't want, or cannot use foreach?
I can't see any way to do this with out a loop, but with a loop it's easy:
function merge_your_arrays ($days, $clicks) {
foreach ($days as $k => $v) {
if (isset($clicks[$k])) {
$days[$k] = array_merge($days[$k],$clicks[$k]);
}
}
return $days;
}
$final = merge_your_arrays($days, $clicks);
精彩评论