我使用while循环来回显PHP数组:
$connect = mysqli_connect("localhost", "user", "password", "db");
$sql = "SELECT * FROM table ORDER BY RAND() LIMIT 0,4";
$result = mysqli_query($connect, $sql);
if(mysqli_num_rows($result) > 0)
{
echo'<section>
<div class="container">
<div class="row">
<h2 class="bold">title</h2>
<hr> ';
while($row = mysqli_fetch_array($result))
{
echo'
<div class="col-sm-3 col-md-3 col-md-push-3">
<div class="portfolio-wrapper">
<div class="portfolio-single">
<div class="portfolio-thumb">
<a href="'.$row['link']." target="_blank"> <img src="'.$row['image'].'" class="img-responsive" alt="'.$row['alt']."></a>
</div>
</div>
<div class="portfolio-info" dir="rtl">
<a href="'.$row['link2']." target="_self"><h2> </h2>
<h6>'.$row['title'].</h6>
</a>
</div>
</div>
</div>';
}
echo'
</div>
</div>
</section';
}
?>
这段代码对我来说很好,但问题是我需要回应4种不同的代码
例如:
first will be: <div class="col-sm-3 col-md-3 col-md-push-9">
second: <div class="col-sm-3 col-md-3 col-md-push-3">
third: <div class="col-sm-3 col-md-3 col-md-pull-3">
last: <div class="col-sm-3 col-md-3 col-md-pull-9">
任何想法如何使用while循环完成此结构?
答案 0 :(得分:4)
使用计数器,并将您的类放入如下数组中:
$classes = [
"col-sm-3 col-md-3 col-md-push-9",
"col-sm-3 col-md-3 col-md-push-3",
"col-sm-3 col-md-3 col-md-pull-3",
"col-sm-3 col-md-3 col-md-pull-9"
];
$i = 0;
while($row = mysqli_fetch_array($result)) {
if ($i > 3) {
$i = 0;
}
?>
<div class="<?php echo $classes[$i]; ?>">
Your content comes here
</div>
<?php
$i++;
}
注意强>
如果数组中没有类似索引,则重置计数器。您的脚本假定您将始终获得4行。
答案 1 :(得分:0)
<?php
$connect = mysqli_connect("localhost", "user", "password", "db");
$sql = "SELECT * FROM table ORDER BY RAND() LIMIT 0,4";
$result = mysqli_query($connect, $sql);
$i = 1;
$count = count($result);
if(mysqli_num_rows($result) > 0)
{
echo'<section>
<div class="container">
<div class="row">
<h2 class="bold">title</h2>
<hr> ';
while($row = mysqli_fetch_array($result))
{
if($i==1){echo '<div class="col-sm-3 col-md-3 col-md-push-9">';}
elseif($i == $count){echo '<div class="col-sm-3 col-md-3 col-md-pull-9">';}
elseif($i%2 == 0){echo '<div class="col-sm-3 col-md-3 col-md-push-3">';}
elseif($i%3 == 0){echo '<div class="col-sm-3 col-md-3 col-md-pull-9">';}
echo'
<div class="portfolio-wrapper">
<div class="portfolio-single">
<div class="portfolio-thumb">
<a href="'.$row['link']." target="_blank"> <img src="'.$row['image'].'" class="img-responsive" alt="'.$row['alt']."></a>
</div>
</div>
<div class="portfolio-info" dir="rtl">
<a href="'.$row['link2']." target="_self"><h2> </h2>
<h6>'.$row['title'].</h6>
</a>
</div>
</div>
</div>';
$i =$i+1;
}
echo'
</div>
</div>
</section';
}
?>