2015-10-15 17 views
1

我有一些項目的數組。每個數組可以有(或不)有子項目,也有一些項目。如何在循環中調用子數組?這很難描述,這裏是代碼。我知道代碼/語法是不正確的,但語法應該澄清我的問題:如何循環陣列中的數組(動態導航)

<?php 
$subitemsA = array(
    'subA1' => array('num'=>65, 'text'=>'Labor', 'url'=>'#'), 
    'subA2' => array('num'=>44, 'text'=>'Rare', 'url'=>'#'), 
); 

$subitemsB = array(
    'subB1' => array('num'=>0, 'text'=>'subB1', 'url'=>'#'), 
    'subB2' => array('num'=>0, 'text'=>'subB2', 'url'=>'#'), 
    'subB3' => array('num'=>0, 'text'=>'subB3', 'url'=>'#') 
); 

$navArray = array(
    'Home' => array('num'=>0, 'text'=>'Home', 'url'=>'#'), 
    'Info' => array('num'=>0, 'text'=>'Info', 'url'=>'#', 'subArray'=>$subitemsA), 
    'Sport' => array('num'=>0, 'text'=>'Sport', 'url'=>'#', 'subArray'=>$subitemsB), 
); 


$html = ''; 
foreach($navArray as $item) { 
    $html .= "<li>"; 
    $html .= "<a href='{$item['url']}'><i class='abc'></i>{$item['text']}</a>\n"; 

    if (count($navArray) > 3) { 

     foreach($navArray.subArray as $subitem) { 
      $html .= "<li>"; 
      $html .= "<a href='{$subitem['url']}'>{$subitem['text']}</a>\n"; 
      $html .= "</li>"; 
     } 

    } 

    $html .= "</li>"; 
} 

第一個foreach循環的作品。但是,我怎樣才能訪問Info和Sport的子陣列呢?

回答

1

你需要爲這個三級的foreach工作 -

foreach($navArray as $key => $item) { 
    $html .= "<li>"; 
    $html .= "<a href='{$item['url']}'><i class='abc'></i>{$item['text']}</a>\n"; 
    foreach ($item as $itemkey => $value) { 
    if (is_array($value)) { //Now Check if $value is an array 
     foreach($value as $valuekey => $subitem) { //Loop through $value 
     $html .= "<li>"; 
     $html .= "<a href='{$subitem['url']}'>{$subitem['text']}</a>\n"; 
     $html .= "</li>"; 
     } 
    } 
    } 
    $html .= "</li>"; 
} 
1

這是回答你的問題在更一般的方式:如何處理使用遞歸和模板多層次的嵌套數組。

function parseArray(array $navArray, &$html, $depth = 0) { 
    foreach ($navArray as $item) { 
    $html .= "<li>"; 

    // this function use template to create html 
    $html .= toHtml($item['url'], $item['text'], $depth); 

    foreach ($item as $subItem) { 
     if (is_array($subItem)) { 
     // use recursion to parse deeper level of subarray 
     parseArray($item, $html, $depth + 1); 
     } 
    } 

    $html .= "</li>"; 

    } 
} 

function toHtml($url, $text, $depth) 
{ 
    $template = ''; 
    if ($depth == 0) { 
    $template = '<a href=\'{{url}}\'><i class=\'abc\'></i>{{text}}</a>\n'; 
    } elseif ($depth >= 1) { 
    $template = '<a href=\'{{url}}\'>{{text}}</a>\n'; 
    } 
    // define more template for deeper level here if you want 

    $template = str_replace('{{url}}', $url, $template); 
    $template = str_replace('{{text}}', $text, $template); 
    return $template; 
} 

$html = ''; 
parseArray($navArray, $html); 

只是暫時忘記了這段代碼,還沒有測試它。希望它有幫助。

Regards,