开发者

Iterating through a PHP array and inserting another array without overwriting

开发者 https://www.devze.com 2023-01-21 09:18 出处:网络
I am looping through an array, and for each value, I need to insert another array containing a few items.The below code inserts the array fine:

I am looping through an array, and for each value, I need to insert another array containing a few items. The below code inserts the array fine:

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

  $schedule[$Key] = array( 
                           array('event_id' => 'test开发者_如何学编程', 
                                 'start_date_time' => 'test',
                                 'end_date_time'=>'test'), ));
endforeach;

And this gives me something like the below:

    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] => 
)

My problem is that I need to insert more than one array for each key, and if i do this, I overwrite the previous entrance.

I think I need to increment the [0] => Array value shown above.

How can this be done?


Update:

I just realized that you always will get only one "child" element per array element, as each $Key is unique in an array anyway. That means you will never have two loops with the same $Key value.
Proof: http://codepad.org/1g4Kjccc

So if you want to insert more than one array for each key, you would have to create these arrays in one loop, e.g.:

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

Maybe you have to show your "source" array and to explain how you want to create entries...


Old answer: (not wrong but does not make much of a difference ;) (as long as $schedule does not already contain values!))
I think you want:

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

You are right, that you are constantly overwriting the value... by initializing the element $schedule[$Key] as array once and by using $schedule[$Key][], you append the new value to the array.

See the PHP array manual.

0

精彩评论

暂无评论...
验证码 换一张
取 消