我有以下代码,用Category
字段将结果数组拆分。
$query = "SELECT * FROM livestock
WHERE Category = 'monitor'
OR Category ='bearded'
OR Category ='chameleon'
OR Category ='skink'
OR Category ='small'
OR Category ='medium'
OR Category ='terrestrial'
OR Category ='arboreal'
OR Category ='leopard'";
$result = mysqli_query($con, $query) or die(mysqli_error($con));
$rows = array();
while ( $row = mysqli_fetch_array($result)){
$rows[$row['Category']][] = $row;}
然后我使用以下代码在几个地方回显这个页面:
foreach($rows['MONITOR'] as $row)
{
$commondraft = $row['Name'];
$current = $row['Category'];
if($current==$previous){
echo"<a href='/stocklist/".$row['id']."/".commonName($commondraft)."' class='row'>";
echo"<div class='common'>".$row['Name']."</div>";
echo"<div class='descr'>".$row['Description']."</div>";
echo"<div class='sex'>".$row['Sex']."</div>";
echo"<div class='age'>".$row['Age']."</div>";
echo"<div class='size'>".$row['Size']."</div>";
echo"<div class='origin'>".$row['Origin']."</div>";
echo"<div class='scientific'>".$row['Scientific']."</div>";
echo"<div class='prices'>".$row['Price']."</div>";
echo"</a>";
}
$previous = $current;
}
echo"</div>";
但每次我使用foreach()
循环回应它时,它会错过第一条记录。
我如何解决这个问题以及导致问题的原因?
提前致谢
答案 0 :(得分:2)
我的猜测是,这是由循环中的以下行引起的:
if($current==$previous){
由于您只在$current
等于$previous
时才输出链接,因此问题是您是否在foreach循环之前正确初始化$previous
。您需要在循环之前使用以下内容初始化$previous
:
$previous = $rows['MONITOR'][0]['Category'];