2012-02-10 53 views
0

我想通过foreach只遍历PHP中的特定子数组。例如数组:通过特定的关联数组在PHP中循环

$testData = array( 
    $test1=array( 
     'testname'=>'Test This', 
     'testaction'=>'create user', 
     $testData = array(
      'item'=>'value', 
      'foo'=>'bar', 
      'xyz'=>'value' 
     ), 
     $anotherArray = array() 
    ), 
    $test2=array( 
     'testname'=>'Test That', 
     'testaction'=>'get user', 
     $testData = array(
      'item'=>'value', 
      'foo'=>'bar', 
      'xyz'=>'value' 
     ), 
     $anotherArray = array() 
    ) 
); 

,现在我要去通过每个测试和设置基础上的名字和行动一些逻辑,但随后需要进行数据的多次测试。不知道如何获得$ test1的$ testData而不是$ test1的$ anotherArray数据。我有以下但它不起作用:

foreach($testData as $test => $section){ 
    foreach($section['testData'] as $field => $value){ 
     \\code 
    } 
} 

任何帮助表示赞赏!谢谢!

+0

'$ testData1'是不是正确构建阵列。你应该收到一个错误。使用Laverdure的答案,您可以使用'$ testData ['test1'] ['testData']'来访问您的数据。 – Josh 2012-02-10 20:53:22

+0

你用'$ testData1'指的是什么@Josh – jheep 2012-02-10 20:57:31

+0

对不起,这是一个错字。我只是想'$ testData'。 – Josh 2012-02-10 20:58:24

回答

1

试试这个:

$testData = array( 
'test1'=>array( 
    'testname'=>'Test This', 
    'testaction'=>'create user', 
    'testData' => array(
     'item'=>'value', 
     'foo'=>'bar', 
     'xyz'=>'value' 
    ), 
    'anotherArray' => array() 
), 
'test2'=>array( 
    'testname'=>'Test That', 
    'testaction'=>'get user', 
    'testData' => array(
     'item'=>'value', 
     'foo'=>'bar', 
     'xyz'=>'value' 
    ), 
    'anotherArray' => array() 
) 
); 
+0

谢谢!它现在似乎在工作。 – jheep 2012-02-10 21:03:19