阵列未合并在一起

时间:2019-04-02 20:07:19

标签: php arrays

因此,我尝试将以下两个数组合并在一起,第一个数组为$ weekDays:

Array
(
[0] => Array
    (
        [id] => 1
        [start] => 11:00:00
        [end] => 17:00:00
    )

[1] => Array
    (
        [id] => 2
        [start] => 09:00:00
        [end] => 17:00:00
    )

[2] => Array
    (
        [id] => 3
        [start] => 09:00:00
        [end] => 17:00:00
    )

[3] => Array
    (
        [id] => 5
        [start] => 09:00:00
        [end] => 17:00:00
    )

[4] => Array
    (
        [id] => 6
        [start] => 09:00:00
        [end] => 17:00:00
    )

[5] => Array
    (
        [id] => 7
        [start] => 09:00:00
        [end] => 17:00:00
    )

[6] => Array
    (
        [id] => 8
        [start] => 09:00:00
        [end] => 17:00:00
    )

)

第二个数组为$ all_slots:

Array
(
    [0] => 0
    [1] => 0
    [2] => 2
    [3] => 0
    [4] => 0
    [5] => 0
    [6] => 0
    [7] => 0
)

使用此foreach,我尝试循环每个$ weekDays项并将其与具有相同索引号的$ all_slots项合并:

foreach($weekDays as $index => $day){
        $slot = ['slot' => $all_slots[$index]];
        array_merge_recursive($slot, $day);
    }

但是当我回显更新的$ weekDays数组时,它根本没有被合并,也没有错误。由于某种原因,它真的什么也不做,我在这里想念什么?我尝试为$ weekDays数组获得以下结果:

Array
(
[0] => Array
    (
        [id] => 1
        [start] => 11:00:00
        [end] => 17:00:00
        [slot] => 0
    )

[1] => Array
    (
        [id] => 2
        [start] => 09:00:00
        [end] => 17:00:00
        [slot] => 0
    )

[2] => Array
    (
        [id] => 3
        [start] => 09:00:00
        [end] => 17:00:00
        [slot] => 2
    )

[3] => Array
    (
        [id] => 5
        [start] => 09:00:00
        [end] => 17:00:00
        [slot] => 0
    )

[4] => Array
    (
        [id] => 6
        [start] => 09:00:00
        [end] => 17:00:00
        [slot] => 0
    )

[5] => Array
    (
        [id] => 7
        [start] => 09:00:00
        [end] => 17:00:00
        [slot] => 0
    )

[6] => Array
    (
        [id] => 8
        [start] => 09:00:00
        [end] => 17:00:00
        [slot] => 0
    )

)

1 个答案:

答案 0 :(得分:2)

array_merge_recursive()返回一个未捕获的结果数组。

一种更简单的方法是

foreach($weekDays as $index => &$day){
    $day['slot'] = $all_slots[$index];
}
  

您必须确保$all_slots数组的发生次数与weekDays相同或更多