通过PHP数组迭代并插入另一个数组而不覆盖

Ben*_*Ben 0 php arrays

我循环遍历一个数组,对于每个值,我需要插入另一个包含几个项目的数组.下面的代码插入数组:

foreach($events as $Key => $val):

  $schedule[$Key] = array( 
                           array('event_id' => 'test', 
                                 'start_date_time' => 'test',
                                 'end_date_time'=>'test'), ));
endforeach;
Run Code Online (Sandbox Code Playgroud)

这给了我类似下面的内容:

    Array
(
    [1287039600] => 
    [1287043200] => 
    [1287050400] => 
    [1287054000] => 
    [1287054900] => 
    [1287057600] => 
    [1287061200] => 
    [1287064800] => Array
        (
            [0] => Array
                (
                    [event_id] => 'test'
                    [start_date_time] => 'test'
                    [end_date_time] => 'test'
                )

        )

    [1287068400] => 
    [1287072000] => 
    [1287075600] => 
)
Run Code Online (Sandbox Code Playgroud)

我的问题是我需要为每个键插入多个数组,如果我这样做,我会覆盖前一个入口.

我想我需要增加上面显示的[0] =>数组值.

任何人都可以建议如何做到这一点?

问候,本.

Fel*_*ing 5

更新:

我只是意识到每个数组元素总是只会得到一个"子"元素,因为每个元素$Key在数组中都是唯一的.这意味着你永远不会有两个具有相同$Key值的循环.
证明:http://codepad.org/1g4Kjccc

因此,如果要为每个键插入多个数组,则必须在一个循环中创建这些数组,例如:

$schedule[$Key] = array(array('event_id' => 'test', 
                              'start_date_time' => 'test',
                              'end_date_time'=>'test'),
                        array('event_id' => 'test', 
                              'start_date_time' => 'test',
                              'end_date_time'=>'test')
                        );
Run Code Online (Sandbox Code Playgroud)

也许你必须展示你的"源"数组并解释你想如何创建条目......


老答案:((只要不是错误的,但并没有太大的差别)$schedule!没有包含值))
我想你想:

foreach($events as $Key => $val) {
  if(!isset($schedule[$Key])) {
    $schedule[$Key] = array();
  }
  $schedule[$Key][] = array('event_id' => 'test', 
                            'start_date_time' => 'test',
                            'end_date_time'=>'test');
}
Run Code Online (Sandbox Code Playgroud)

你是对的,你不断地覆盖价值......通过将元素初始化$schedule[$Key]为数组一次并使用$schedule[$Key][],新值附加到数组中.

请参阅PHP数组手册.