简体   繁体   中英

How do I detect the last iteration in while loop

I tried doing this first:

$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";
  }
}

Here it never detects the last one. I also tried this:

$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";
  }
}

Here it detects every iteration as the last one.

Does anyone how to make it detect the last iteration?

The $objectsid variable is storing the mysql_result object not the array of your fetched rows. So even if you apply count($objectsid) , you will not get the length of your fetched array.

So the right method is to use mysql_num_rows() .

So Simply do this $len=mysql_num_rows($objectsid); and the rest will workout as you are expecting. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM