views:

55

answers:

2

How would I insert a key => value pair into the midst of a nested array?

example:

array
  1 => string 'a' (length=1)
  2 => string 'b' (length=1)
  3 => 
    array
      'this' => string 'that' (length=4)
      'meh' => string 'foo' (length=3)
      'blah' => 
        array
          'a' => int 1
          'b' => int 2
  4 => 
    array
      'this' => string 'that' (length=4)
      'meh' => string 'foo' (length=3)
      'blah' => 
        array
          'a' => int 1
          'b' => int 2

How would I add x=>1 to every second level of array... so I would get this:

 array
  1 => string 'a' (length=1)
  2 => string 'b' (length=1)
  3 => 
    array
      'this' => string 'that' (length=4)
      'meh' => string 'foo' (length=3)
      'blah' => 
        array
          'a' => int 1
          'b' => int 2
      'x' => int 1 //Here's the added bit
  4 => 
    array
      'this' => string 'that' (length=4)
      'meh' => string 'foo' (length=3)
      'blah' => 
        array
          'a' => int 1
          'b' => int 2
       'x' => int 1 //Here's the added bit
+2  A: 
$array[3]['x'] = 1;
$array[4]['x'] = 1;

Or, if you were looking for something automated on an array of indefinite length:

foreach ($array as &$node) {
    if (is_array($node)) {
        $node['x'] = 1;
    }
}
deceze
Why is the ampersand needed in front of the $node variable?
rg88
@rg88 To modify the actual array value: http://php.net/manual/en/control-structures.foreach.php
deceze
A: 
if(!is_array($array1['property']))
{
    $array1['property'] = array();
}

$array1['property']['x'] = 1;
mark_dj