2012-02-28 75 views
0

我有多維數組的這種組合,但我不能打印正確的值在屏幕上,打印一個,兩個的組合的值,和三維陣列

$parent = array(
    array(
     'function_name' => 'home', 
     'screen_name' => 'Home' 
     ), 

    array(
     'function_name' => 'categories', 
     'screen_name' => 'Categories', 


     array(
      'function_name' => 'post', 
      'screen_name' => 'Post', 
      ) 
     ), 

    array(
     'function_name' => 'pages', 
     'screen_name' => 'Pages', 


     array(
      'function_name' => 'add', 
      'screen_name' => 'Add', 

      array(
       'function_name' => 'manage', 
       'screen_name' => 'Manage' 
       ) 
      ) 
     ) 
); 

某些陣列有的是用sub數組,有的子數組有subsub數組。

foreach($parent as $index => $item) 
{ 
    echo 'parent - '.$item['screen_name'].'<br/>'; 

    foreach($item as $child) 
    { 
     echo 'child - '.$child['screen_name'].'<br/>'; 

     foreach($child as $grandchild) 
     { 
      echo 'grandchild - '.$grandchild['screen_name'].'<br/>'; 
     } 
    } 
} 

錯誤信息,

Warning: Invalid argument supplied for foreach() in -> foreach($child as $grandchild) 

我尋找的是這樣的結果,

parent - Home 
parent - Categories 
    child - Post 
parent - Pages 
    child - Add 
    grandchild - Manage 

編輯:

我用這個測試下方嘗試,

foreach ($system as $inner_1) { 

    if (is_array($inner_1)) 
    { 

     foreach ($inner_1 as $inner_2) 
     { 

      if (is_array($inner_2)) 
      { 
        foreach ($inner_2 as $inner_3) 
        { 
        var_dump($inner_3['function_name']); 
        } 
      } 
     } 
    } 
} 

但我得到一個奇怪的結果,

string 'p' (length=1) // don't know why I get this. 
string 'P' (length=1) // don't know why I get this. 

string 'a' (length=1) // don't know why I get this. 
string 'A' (length=1) // don't know why I get this. 

string 'manage' (length=6) // correct result. 

回答

0

當運行$parent[1]foreach($item as $child)$child採用以下值:'home''Home'和陣列。

保持數組完全關聯怎麼樣?

$parent = array(
    array(
     'function_name' => 'categories', 
     'screen_name' => 'Categories', 
     'children' => array(
      array(
       'function_name' => 'post', 
       'screen_name' => 'Post' 
      ), 
      array(
       'function_name' => 'review', 
       'screen_name' => 'Review', 
       'children' => array(
        ... 
       ) 
      ), 
     ) 
    ) 
); 

這樣你就可以運行foreach ($item['children'] as $child)知道參數是一個數組(你需要確保$item['children']存在,並且是一個數組)。

+0

感謝您的建議,但家長通常有不止一個孩子,這項工作? – laukok 2012-02-28 00:52:05

+0

@lauthiamkok:我的錯 - 我修復了我的帖子。 – juanrpozo 2012-02-28 08:27:30

+0

感謝編輯,juanrpozo :-) – laukok 2012-02-28 16:35:42