2

我有一个网站,我正在使用 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 循环中获取键和值呢?

4

4 回答 4

1

您可以使用array_chunk将数组拆分为两个单独的块,然后遍历每个块:

$chunked = array_chunk($array, 6);
于 2012-09-25T04:16:16.517 回答
1

尝试使用 slice()

$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);
于 2012-09-25T04:19:17.163 回答
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);
于 2012-09-25T04:51:52.440 回答
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>
}

放入必要的打开/关闭 php 标签

于 2012-09-25T05:17:43.227 回答