1

I have the following code:

$query6 = "SELECT TIMESTAMP As sDate, COUNT( TIMESTAMP ) AS Total 
           FROM tresults GROUP BY TO_DAYS( timestamp ) ";

$result6 = $mysqli->query($query6);

while($row6 = $result6->fetch_row())
    {
        $dt = new DateTime($row6[0]);
        $sd = $dt->format('M j');

        echo "['".$sd."',  ".$row6[1]."],";

    }

This works fine, but what I am struggling with is that I need the echo to be different the for the last one in the loop. It needs to be (the comma is missing after the ] for reference):

    echo "['".$sd."',  ".$row6[1]."]";  

I've been trying to do a count of the number of arrays but cannot get that to work. Any suggestions welcomed.

2
  • 2
    You could just add them into an array ($yourArray[] = "['".$sd."', ".$row6[1]."]";) then implode(',', $yourArray) after your while statement. Commented Jun 5, 2014 at 18:16
  • You could do that but what about much simpler: call substr($sd, 0, -1) after the while? Commented Jun 5, 2014 at 18:17

1 Answer 1

3

You can get the total number of rows and define a counter. After that you can compare them in the loop :

$result6 = $mysqli->query($query6);
$num = $resut6->num_rows;
$i = 0;
while($row6 = $result6->fetch_row())
{
    if($num != $i){
       /* code for all elements except the last one*/
    } else {
       /* code for the last element*/
    }
    $i++;
}

Or you can do something like this using implode() :

$final = array();
while($row6 = $result6->fetch_row()){
    $dt = new DateTime($row6[0]);
    $final[] =  "['" . $dt->format('M j') . "',  ".$row6[1]."]";
}
echo implode(', ', $final);
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect (small change to variable need from $resukt6 to $result6!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.