2011-07-19 104 views
1

你好,我有以下代碼來生成我的導航/頁面菜單,並將樣式元素應用到活動頁面。我想知道如何才能凝聚代碼而不是擁有兩個合併數組?凝聚PHP數組?

這是我目前的代碼,兩者之間的區別是html鏈接輸出。 「首頁」鏈接必須是<a href="./'. $k .'">'. $v .'</a>

而其它頁面需要有<a href="./?p='. $k .'">'. $v .'</a>

<?php 

    $current = array(
    "" => "Home" 
    ); 
    foreach($current as $k => $v) { 
     $active = $_GET['p'] == $k 
     ? ' class="current_page_item"' 
     : ''; 
    echo '<li'. $active .'><a href="./'. $k .'">'. $v .'</a></li>'; 
    } 

    $current = array(
     "contact" => "Contact Us", 
     "about" => "About Us", 
     "privacy" => "Privacy Policy" 
    ); 
    foreach($current as $k => $v) { 
     $active = $_GET['p'] == $k 
      ? ' class="current_page_item"' 
      : ''; 
     echo '<li'. $active .'><a href="./?p='. $k .'">'. $v .'</a></li>'; 
    } 

?> 

任何幫助將不勝感激,謝謝:)

+0

'if($ v!=「Home」)$ k ='?p ='。 $ k'是你需要有一個循環的唯一改變... –

回答

1
<?php 

$current = array(
    "" => "Home" 
    "contact" => "Contact Us", 
    "about" => "About Us", 
    "privacy" => "Privacy Policy" 
); 
foreach($current as $k => $v) { 
    $active = $_GET['p'] == $k 
     ? ' class="current_page_item"' 
     : ''; 
    echo '<li'. $active .'><a href="./'.(empty($k)?"":"?p=") . $k .'">'. $v .'</a></li>'; 
} 

?> 
1

幾乎相同

$ href = empty($ k)? 「./」:「./?p={$k}」;