任何人都可以帮我限制每个div的数据显示吗?示例我有10条记录,我希望每个div显示3条记录。
输出样本:
姓名|年龄
A | 11
B | 13
C | 11
姓名年龄
D | 10个
C | 13个
E | 11个
姓名年龄
F | 10个
G | 13个
H | 11个
姓名年龄
J | 9
代码:
foreach ( $datas as $data ) {
echo "<div>";
echo "Name | Age";
echo "<div>".$data->name."|". $data->age;
echo "</div>"
}
提前致谢。
答案 0 :(得分:1)
这应该适合你:
// this is to have the numeric keys that I will use later on
$datas = array_values($datas);
echo '<div>';
foreach ( $datas as $key => $data ) {
if ($key % 3 == 0 && $key > 0) {
echo '</div><div>';
}
echo 'Name | Age';
echo '<div>'.$data->name.'|'. $data->age .'</div>';
}
echo '</div>';
这里有一个简单数组的示例,用于说明代码的作用:
$datas = array(0.00, 0.2459, 0.688, 0.5, 10, 77, 36);
// This is used to remove the 'Chars' keys you added to the array following your comment
$datas = array_values($datas);
echo '<div>';
for ( $i = 0; $i < count($datas); $i++ ) {
if ($i % 3 == 0 && $i > 0) {
echo "</div><div>";
}
echo "Name | Age = ";
echo $datas[$i] . ' * ';
}
echo '</div>';
将输出(我为了更好的可见性添加了断裂线):
<div>Name | Age = 0 * Name | Age = 0.2459 * Name | Age = 0.688 * </div>
<div>Name | Age = 0.5 * Name | Age = 10 * Name | Age = 77 * </div>
<div>Name | Age = 36 * </div>
答案 1 :(得分:0)
您可以使用模运算符来检查迭代是否是3的倍数
即使您的密钥不是数字,此示例也应该有效:
$i = 0 ;
echo "<div>";
echo "Name | Age";
foreach ($datas as $data ) {
// if it's multiple of 3 you need a new div (return boolean)
$newDiv = $i++ % 3 == 0;
if ($newDiv && $i > 1) {
echo "</div>";
echo "<div>";
echo "Name | Age";
}
echo "<div>".$data->name."|". $data->age . "</div>";
}
echo "</div>";