PHP,推阵列递归foreach循环内

问题描述:

考虑以下数组PHP,推阵列递归foreach循环内

$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) 

      ) 


    */ 

这给了我一个很头疼......并且似乎无法找到解决方案..非常感谢您的帮助提前..

+1

我不是很确定你想达到什么目的吗?你能澄清一些吗? – Oldskool 2011-12-29 13:06:40

+0

@ user1099862你需要告诉我们你的真正目标是什么,而不是它的一些抽象版本。 – jezmck 2011-12-29 13:08:45

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; 
+0

太棒了,谢谢..我会保持第二个选项,因为在真实的例子中我不知道密钥的名字.. – user1099862 2011-12-29 13:36:17

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

不会影响原始数组,只有'foreach'块内的副本。 – Matmarbon 2011-12-29 13:36:53

貌似

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

将是最快的方式ô.O

你为什么不使用类似的东西:

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

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

或者如果你知道的地方:

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

你也可以尝试做替代$value$value_来引用,所以通过&$value&$value_取代他们在第2和7,那么你应该能够你想(array_push

编辑的内容:请注意这不是直到PHP 5