按键合并两个数组,但保留PHP中第一个的键,array_combine失败

时间:2021-07-29 12:18:25

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.

在第二个数组中,如果没有单击,则索引不存在。我尝试过array_combine,但需要使用相同的键,array_merge失败。

What option I have?

我有什么选择?

Thank you in advance

提前谢谢你

2 个解决方案

#1


3  

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

看看PHP.net上的array_merge_recursive函数。此外,请查看那里的注释,以查找其中一个函数是否提供所需的数组(即注释#104145和注释#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?

另外,请注意,使用foreach,最终一定会得到所需的数组。你有什么特别的理由不想要或者不能使用foreach吗?

#2


2  

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);

#1


3  

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

看看PHP.net上的array_merge_recursive函数。此外,请查看那里的注释,以查找其中一个函数是否提供所需的数组(即注释#104145和注释#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?

另外,请注意,使用foreach,最终一定会得到所需的数组。你有什么特别的理由不想要或者不能使用foreach吗?

#2


2  

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);