我有一个阵列;以下
$arr = array(
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
);
我希望打印类似
的内容我的代码只打印前3个
for($m = 0; $m < 9; $m++){
echo "<ul>";
for($i = 0; $i <3; $i++){
echo "<li>";
echo $arr[$i];
echo "</li>";
}
echo "</ul>";
}
真的很感激!
答案 0 :(得分:2)
您可以使用php array_chunk($arr,number of chunk)
$arr = array( '1', '2', '3', '4', '5', '6', '7', '8', '9');
$chunkArray = array_chunk($arr,3);
foreach ($chunkArray as $key => $value) {
echo '<ul>';
foreach ($value as $key1 => $value1) {
echo '<li>'.$value1.'</li>';
}
echo '</ul>';
}
答案 1 :(得分:1)
一种选择是使用modulo
(%
),例如:
$arr = array(
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
);
$perGroup = 3;
for($m = 0; $m < count($arr); $m++){
if ( $m % $perGroup === 0 ) echo "<ul>";
echo "<li>";
echo $arr[$m];
echo "</li>";
if ( $m % $perGroup === ( $perGroup - 1 ) || $m === ( count($arr) - 1 ) ) echo "</ul>";
}
这将导致:
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<ul>
<li>4</li>
<li>5</li>
<li>6</li>
</ul>
<ul>
<li>7</li>
<li>8</li>
<li>9</li>
</ul>
答案 2 :(得分:0)
试试这个
$arr = array(
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
);
$i=0;
echo "<ul>";
foreach($arr as $value)
{
if($i ==3)
{
echo "</ul><p></p><ul>";
$i=0;
}
echo "<li>";
echo $value;
echo "</li>";
$i++;
}
echo "</ul>";