views:

74

answers:

2

Hi guys,

How is is possible, using PHP to add a new index to each 'level' of an multidimensional array?

For instance, for the following array:

$array = array(
    'a' => 'a val',
    'b' => array(
        'ba' => 'ba value',
        'bb' => array(
            'bba' => 'bba value'
        ),
        'bc' => 'bc value'
    ),
    'c' => 'c val',
    'd' => 'd val'
);

... would turn into:

$array = array(
    'a' => 'a val',
    'b' => array(
        'ba' => 'ba value',
        'bb' => array(
            'bba' => 'bba value',
            'new index' => 'new index value'
        ),
        'bc' => 'bc value',
        'new index' => 'new index value'
    ),
    'c' => 'c val',
    'd' => 'd val',
    'new index' => 'new index value'
);

Thanks in advance,
titel

+1  A: 
function addIndex($arr){
  if(!is_array($arr)){ return; }
  foreach($arr as &$a){
    if(is_array($a)){
      $a = addIndex($a);
    }
  }
  $arr['new index'] = 'new index value';
  return $arr;
}
thephpdeveloper
you need a pass by reference, or else to assign the result of addIndex back to $arr i think?
benlumley
the function you proposed is only adding the new index to the first level of the array, not the other as well :(
titel
thephpdeveloper
+1  A: 

The corrected function from the phpdeveloper

function addIndex($arr){
  if(!is_array($arr)){ return; }
  foreach($arr as &$a){
    if(is_array($a)){
      $a = addIndex($a);
    }
  }
  $arr['new index'] = 'new index value';
  return $arr;
}
Exception e