Search code examples
phparraysarray-merge

Add New Rows To Array


I have an array which looks like the following:

Array (
 [class_name] => Array ( [0] => 1 [1] => 2 )
 [zone1_price] => Array ( [0] => 1 [1] => 2 )
 [zone2_price] => Array ( [0] => 1 [1] => 2 )
 [zone3_price] => Array ( [0] => 1 [1] => 2 )
 [zone4_price] => Array ( [0] => 1 [1] => 2 ) 
)

I want to be able to add new rows which will be:

Array (
 [class_name] => Array ( [0] => 3 )
 [zone1_price] => Array ( [0] => 3 )
 [zone2_price] => Array ( [0] => 3 )
 [zone3_price] => Array ( [0] => 3 )
 [zone4_price] => Array ( [0] => 3 )
)

which would then become:

Array (
 [class_name] => Array (  [0] => 1 [1] => 2 [2] => 3 )
 [zone1_price] => Array ( [0] => 1 [1] => 2 [2] => 3 )
 [zone2_price] => Array ( [0] => 1 [1] => 2 [2] => 3 )
 [zone3_price] => Array ( [0] => 1 [1] => 2 [2] => 3 )
 [zone4_price] => Array ( [0] => 1 [1] => 2 [2] => 3 )
)

I am thinking I will need to use array_merge but I also think I need to separate the arrays, give them a key of some sort then combine them and add then array them.

Where would I start with something like this?


Solution

  • You can do it like this

    <?php
      $first=array(
        'class_name'=>array(1,2),
        'zone1_price'=>array(1,2),  
        'zone2_price'=>array(1,2),  
        'zone3_price'=>array(1,2),  
        'zone4_price'=>array(1,2),
        );
      $second=array(
        'class_name'=>array(3,4),
        'zone1_price'=>array(3,4),  
        'zone2_price'=>array(3,4),  
        'zone3_price'=>array(3,4),  
        'zone4_price'=>array(3,4),  
        );
      $fs=sizeof($first['class_name']);
      $ss=sizeof($second['class_name']);
      foreach($first as $k => $v)
      {
        for($i=$fs;$i<$ss+$fs;$i++)
        {
          $first[$k][$i]=$second[$k][$i-$fs];
        } 
      }