如何获取返回的每个项目的行号

时间:2017-01-15 04:21:25

标签: php

我正在尝试使用XSwitch jquery脚本并动态创建" section id"自动但被卡住了。

如何为每个部分提供一个" id"从0开始?有些项目有2或3个图像,有些有30 +。

$result = mysqli_query($conn,"SELECT * FROM Images WHERE stock=".$_GET['stock']." ORDER BY orderIndex");
while($row = mysqli_fetch_array($result)){
  $count = $result->num_rows;
  if ($count) {
    $photos .= '<div class="section" id="section__NEED___NUMBER" style="background-image: url(inventory/'.$category.'/large/'.$stock.'_'.$row['id'].'.jpg)"></div>';
  } else {
    $photos = 'No Photos are currently available';
  }
}

1 个答案:

答案 0 :(得分:2)

你可以使用一个简单的计数器变量($counter = 0;),你在每个循环中增加($ counter ++;`) -

$counter = 0;
$result = mysqli_query($conn,"SELECT * FROM Images WHERE stock=".$_GET['stock']." ORDER BY orderIndex");
$count = $result->num_rows;
if ($count) {
    $photos = "";
    while($row = mysqli_fetch_array($result)){
        $photos .= '<div class="section" id="section__'.$counter.'" style="background-image: url(inventory/'.$category.'/large/'.$stock.'_'.$row['id'].'.jpg)"></div>';
        $counter++;
    }
} else {
    $photos = 'No Photos are currently available';
}

请注意,您的$count = $result->num_rows;if ($count) {...}圈内有while(),而它应该在外面。