2012-09-25 56 views
2

我有一個網站,我使用PHP的同時打印從陣列迭代通過已知數量的數組元素,並拿到鑰匙PHP

$array = array(
    "gfo" => "Fondant", 
    "gdo" => "Domino", 
    "ges" => "Espir", 
    "gam" => "Amara", 
    "gsa" => "Sandwich", 
    "gme" => "Merme", 
    "cza" => "Zarza", 
    "cor" => "Oreo", 
    "cal" => "Almen", 
    "cca" => "eche", 
    "cch" => "Chocolate" 
); 

鍵和值,但我想只顯示第6個要素像

<li> 
<a href="product1.php" style="padding:8px 30px;">Product 1</a> 
    <ul>     
    <?php foreach($array as $key=>$val):?> 
    <li><a href="http://www.site.com.mx/products.php?id=<?=$key?>"><?=$val?></a></li> 
    <?php endforeach;?> 
    </ul> 
</li> 

在彈出菜單中的其他菜單其他5個元素

<li> 
<a href="product2.php" style="padding:8px 30px;">Product 2</a> 
    <ul>     
    <?php foreach($array as $key=>$val):?> 
    <li><a href="http://www.site.com.mx/products.php?id=<?=$key?>"><?=$val?></a></li> 
    <?php endforeach;?> 
    </ul> 
</li> 

我知道我可以使用

for ($i = 1; $i <= 6; $i++) { 
    echo $i; 
} 

for ($i = 6; $i <= sizeof($array); $i++) { 
    echo $i; 
} 

可是如何才能讓for循環中兩個關鍵和價值?

+0

array_slice()是一種方式 – 2012-09-25 04:16:19

+0

我打算建議,但array_slice不保留關聯數組鍵。 – chaimp

+0

@jeffp只有當它們是數字時(它們不在這裏),並且只有當你不使用標誌時preserve_keys(5.0.2+) – 2012-09-25 04:36:56

回答

1

您可以使用each爲:

$i = 1; reset($array); 
// get the first 6 
while ($i <= 6 && list($key, $val) = each($array)) { 
     echo "$key = $val\n"; 
     ++$i; 
} 

// get the rest  
while (list($key, $val) = each($array)) { 
     echo "$key = $val\n"; 
} 

或者,你可以使用array_slice()但一定要保存鍵:

$first_six = array_slice($array, 0, 6, true); 
$rest = array_slice($array, 6, null, true); 
1

您可以使用array_chunk超過每這些陣列分成兩個單獨的塊,然後遍歷:

$chunked = array_chunk($array, 6); 
1

與片嘗試()

$first_array = slice_array($array,0,6); 
$second_array = slice_array($array,6,10); 

,然後做你的行爲,你還可以使用

$first_array = array_chunk($array,6); 
$second_array = array_chunk($array,6,10); 
+0

downvote的原因.. ?? – Gautam3164

0

使用array_keys()和array_values()函數

$array = array(
    "gfo" => "Fondant", 
    "gdo" => "Domino", 
    "ges" => "Espir", 
    "gam" => "Amara", 
    "gsa" => "Sandwich", 
    "gme" => "Merme", 
    "cza" => "Zarza", 
    "cor" => "Oreo", 
    "cal" => "Almen", 
    "cca" => "eche", 
    "cch" => "Chocolate" 
); 
$keys = array_keys($array); 
$values = array_values($array); 

for ($i = 0; $i < 6; $i++) { 
    <li><a href="http://www.site.com.mx/products.php?id=<?=$keys[$i]?>"><?=$values[$i]?></a></li> 
} 

for ($i = 6; $i <= sizeof($array); $i++) { 
    <li><a href="http://www.site.com.mx/products.php?id=<?=$keys[$i]?>"><?=$values[$i]?></a></li> 
} 

放入必需品y open/close php標籤