我试图将数组中的前10个项显示为列表项,然后编写一些逻辑,其中包括一个按钮,将数组的其余项显示为list。提前感谢您的帮助!
这是我目前所拥有的
if (count($all_machines) > 10) {
echo '<ul>';
foreach($all_machines as $machine) {
echo '<li>' . $machine['name'] . '</li>';
}
echo '</ul>';
} else {
echo "No machines";
}
使用foreach
将迭代数组的所有项,我建议在此处使用for
。
if (count($all_machines) > 10) {
echo '<ul>';
for ($i=0; $i<10; $i++) {
echo '<li>'.$all_machines[$i]['name'].'</li>';
}
echo '</ul>';
}
如果你也想访问其他值,可以这样做
$count = count($all_machines);
if ($count > 10) {
echo '<ul>';
for ($i=0; $i<10; $i++) {//first 10 elements
echo '<li>'.$all_machines[$i]['name'].'</li>';
}
echo '</ul>';
for ($i=10; $i<$count; $i++) {//all other elements
//do something with $all_machines[$i]
}
}
您可以使用array_slice()
获取数组中的前10个元素,从而仍然可以使用foreach
。
// number of items to display
$display_threshold = 10;
if (count($all_machines) > $display_threshold) {
echo '<ul>';
foreach(array_slice($all_machines, 0, $display_threshold) as $machine)
echo '<li>' . $machine['name'] . '</li>';
echo '</ul>';
} else {
echo 'No machines';
}