php - Foreach - 包含<li> </li>,里面有两个结果,然后重复。

时间:2011-08-24 21:48:40

标签: php arrays foreach counter html-lists

使用php - 我试图在阵列上运行“foreach”,但我想将每两个结果包装在li标签中。输出将如下所示。

<li>

<div>result 1</div>

<div>result 2</div>

</li>

<li>

<div>result 3</div>

<div>result 4</div>

</li>

<li>

<div>result 5</div>

<div>result 6</div>

</li>

我该怎么做呢?

谢谢!

3 个答案:

答案 0 :(得分:9)

$chunks = array_chunk($arr, 2);
foreach ($chunks as $chunk) {
    // $chunk could have either 2 elements, or just one on the last iteration on an array with odd number of elements
    echo '<li>';
    foreach ($chunk as $value) {
        echo '<div>' . $value . '</div>';
    }
    echo '</li>';
}

答案 1 :(得分:1)

$results = array(1, 2, 3, 4, 5, 6);
echo "<li>";
foreach($results as $pos => $result) {
    if ($pos > 2 && $pos % 2 == 0) {
        echo "</li>\n<li>";
    }
    echo "<div>result $result</div>";
}
echo "</li>";

或更简单:

$results = array(1, 2, 3, 4, 5, 6);
$max = count($results);
for($i = 0; $i < $max; $i++) {
    echo "<li>";
    echo "<div>result " . $results[$i] . "</div>";
    $i++;
    echo "<div>result " . $results[$i] . "</div>";
    echo "</li>";
}

答案 2 :(得分:1)

$count = 0;
foreach ($array as $key=>$value) {
    ++$count;
    if ($count == 1) {
        echo "<li>";
        echo "<div>" . $value."</div>";    
    } else {
        echo "<div>" . $value."</div>";    
        echo "</li>";
        $count = 0;
    }
}