Search code examples
phparraysarray-push

PHP array_push() - pushing new data to array


I have an array which looks like this:

Array
(
    [0] => Array
        (
            [1] => Array
                (
                    [name] => vrij
                    // ...
                )

            [2] => Array
                (
                    [name] => zat
                   // ...
                )
         )
)

I build this array using a for loop; however, I need to push 4 more 'records' to the array, which I can't do in this for loop.

I want the array to look like this, after the pushes:

    Array
(      
    [0] => Array
    (
        [1] => Array
            (
                [name] => vrij
              // ...
            )

        [2] => Array
            (
                [name] => zat
               // ...
            )
         // ...
     )
    [1] => Array
    ( 
          [1] => Array
              (
               [name] => zon
               //...
              )
           [2] // etc
     )
)

The four new records should be pushed to array[1], so I get something like

$array[1][0], $array[1][1], etc. 0 1 2 3 contains the new data. 

I tried quite a lot of stuff, to be honest. I need to do four of these pushes, so I was trying a for loop:

for($i = 0; $i < 4; $i++)
    {
        $day_info = $this->get_day_info($i, $data['init']['next_month'], $data['init']['current_year']);
        $push['name'] = $day_info['day_name'];
        array_push($data['dates'], $push);
    }

and all other kinds of things with [], [1][$i], etc. Sometimes it even adds five arrays! I'm confused as to why it won't just add the [1][1], [1][2],.. I'm probably missing out on something here. Thanks a lot.

If this isn't clear, please do tell and I'll add more code to explain the problem better.


Solution

  • $extradates = array(1 => 'zon', 2 => 'maa');
    $data['dates'][] = $extradates;
    

    Will add 2 extra dates to the array using a new index.

    Although if I see what you trying to accomplish, I think there might be a better way.

    This above works though :)