如何检测while循环中的最后一次迭代

时间:2016-10-24 21:52:50

标签: php while-loop

我先尝试这样做:

$e = 0;

$objectsid = mysql_query("SELECT * FROM xw_char_items WHERE CharId = '$charid' AND ItemCat = 'object' ORDER BY SortOrder ASC");

while($obj = mysql_fetch_array($objectsid)) {

  $e++;
  if($e==9) break;

  $objectsinfo = mysql_query("SELECT * FROM xw_objects WHERE ItemId = '{$obj["ItemId"]}'");
  $object = mysql_fetch_array($objectsinfo);

  echo "&charid$e={$char["Id"]}";
  if($objectsid == end($obj)) {
  echo "&intActiveObject=1";
  echo "&intObjectsNum=$e";
  }
}

这里它永远不会检测到最后一个。我也试过这个:

$e = 0;
$len = count($objectsid));

while($obj = mysql_fetch_array($objectsid)) {

  $e++;
  if($e==9) break;

  $objectsinfo = mysql_query("SELECT * FROM xw_objects WHERE ItemId = '{$obj["ItemId"]}'");
  $object = mysql_fetch_array($objectsinfo);
  mysql_free_result($objectsinfo);

  echo "&charid$e={$char["Id"]}";
  if ($e == $len - 1) {
  echo "&intActiveObject=1";
  echo "&intObjectsNum=$e";
  }
}

这里它将每次迭代检测为最后一次。

有人如何让它检测最后一次迭代?

1 个答案:

答案 0 :(得分:-1)

$objectsid变量存储mysql_result对象而非存储的行数组。因此,即使您应用count($objectsid),也不会获得所获取数组的长度。

所以正确的方法是使用mysql_num_rows()

所以,简单地执行此操作$len=mysql_num_rows($objectsid);,其余的将按照您的预期进行锻炼。 :)