PHP,在foreach循环中递归推送数组

时间:2011-12-29 13:03:46

标签: php arrays multidimensional-array

给出以下数组

$a = array(
    'a' => '0',
    'b' => '1',
    'c' => '2',
    'push' => array(
         'd' => '0',
         'e' => '1',
         'here' => array()
    )
);

以下一组循环:

// First level
foreach($a as $key=>$value):

     if($key=='push'):

        //Second level
        foreach($value as $key_=>$value_):

             if($key_=='here'):

              // If this key is found then do some stuff here and get another as a result array
              $thirdArray = array(12, 13, 15);

              // Then, I am looking to push this third array from within this loop 
              // Obviously, it should be placed inside this particular key of the array
              // I am trying something like below which doesn't work

              //array_push($value_, $thirdArray);

              endif;

         endforeach;

     endif;

 endforeach;

/ *打印我的数组的输出应为

  'a' => 'A',
  'b' => 'B',
  'c' => 'C',
      'push' => array(
            'd' => '0',
            'e' => '1',
            'here' => array(

                     array(12, 13, 15)

             )


  */

这让我很头疼......似乎无法找到解决方案..非常感谢您提前帮助..

5 个答案:

答案 0 :(得分:2)

foreach($value as $key_=>$value_):
  if($key_=='here'):
    $thirdArray = array(12, 13, 15);
    $a['push']['here'][] = $thirdArray;
  endif;
endforeach;

foreach($value as $key_=>$value_):
  if($key_=='here'):
    $thirdArray = array(12, 13, 15);
    $a[$key][$key_][] = $thirdArray;
  endif;
endforeach;

答案 1 :(得分:0)

if($key_=='here'):       
    $value[$key_] = array(12, 13, 15);            
endif;

答案 2 :(得分:0)

看起来像

if( isset( $a['push'] ) )
 if( isset( $a['push']['here'] ) )
  $a['push']['here'][] = array(12, 13, 15);

将是最快的方式ô.O

答案 3 :(得分:0)

你为什么不使用这样的东西:

$a[$key][$key_] = array(12, 13, 15);

代替

$thirdArray = array(12, 13, 15);

或者如果你知道这个地方:

$a['push']['here'] = array(12, 13, 15);

答案 4 :(得分:0)

您也可以尝试将$value$value_替换为引用,因此请在{2}和&$value以及&$value_的第2行和第7行中替换它们,然后您应该能够做你想做的事(array_push

编辑:请注意,直到PHP 5