Dear Sirs!

I would like to echo out the last iteration of a while loop differently as the first ones.

This is my code wich echos out the first and the last iteration, but I need the middle iterations as wel..

<?php
// Print
if ($row = mysql_fetch_array($result)) {
  echo '["' .$row[1]. '",' .$row[2].'],';
  $i++;
  while ($row = mysql_fetch_array($result)){
    echo '["' .$row[1]. '",' .$row[2].']';
    $i++;
  } // end while
} // end if

?>

The difference between the last and the other iterations is that the last doesn't contain a comma. But I need the other iterations as well, not just the first and the last ones.. Can you please help me ?

Tibor

<?php



  $comma="";
  while ($row = mysql_fetch_array($result)){
    echo $comma.'["' .$row[1]. '",' .$row[2].']';
    $comma=", ";

  } // end while


?>

check for result

    if($result = mysql_query("SELECT * FROM table")){
        while ($row = mysql_fetch_array($result)){
            // don't echo immediately, store in $string
            $string .= '["' .$row[1]. '",' .$row[2].'],';
        }
    // now $string has an extra comma...
    $string = substr($string, 0, -1);
    }    

use substr() to select all but last character, then echo the whole thing.

Member Avatar

diafol

while($row = mysql_fetch_array($result)){ 
    $array[] = array($row[1],$row[2]);
}
$json = json_encode($array);
echo $json;
Member Avatar

diafol

that's a tidy solution.

I'm assuming it is from a previous thread by the OP. I'm gonna look pretty stupid if it isn't ! :)