-1

I have a problem with my while loop, every item needs to have a comma, but the last one doesn't need one, but i don't know what i need to do...

        while($row = $result->fetch_assoc()) {
        echo "
        {
            id: " . $row['id'] . ",
            dexNr:  " . $row['mon_id'] . ",
            name:  '" . $row['mon_id'] . "',
            expiration:  " . $row['expire_timestamp'] . ",
            lat: " . $row['lat'] . ",
            lng: " . $row['lon'] . "
        },
        ";
    }
  • What are you trying to do? It almost looks like you're trying to generate (invalid) JSON manually (or some other serialization). – Jonnix Aug 28 '17 at 21:01

1 Answers1

1

You could push each item into an array and then implode it with a comma. This will then only put commas between the items but not at the end:

$output = array();

while($row = $result->fetch_assoc()) {
    array_push($output, "
        {
        id: " . $row['id'] . ",
        dexNr:  " . $row['mon_id'] . ",
        name:  '" . $row['mon_id'] . "',
        expiration:  " . $row['expire_timestamp'] . ",
        lat: " . $row['lat'] . ",
        lng: " . $row['lon'] . "
        }
    ");
}

$output = implode(",", $output);
Chris
  • 4,672
  • 13
  • 52
  • 93