-2

I have a question. I try to separate the output from my MySQL database with a comma. Somehow that doesn't work.

PHP code:

echo "[";

if ($result = $con->query("SELECT * FROM table")) {

    while($row = $result->fetch_array(MYSQLI_ASSOC)) {
        $timestamp = strtotime($row['datetime']);


            echo "[" . $timestamp . "000" . "," . $row['temp'] . "]" . ",";


}
}
$result->close();
$con->close();
echo "]";

Output:

[[1591072800000,12.5],[1591073100000,12.6], ........ [1591367100000,21.6],[1591367160000,21.5],]

The last comma is too much and has to go.

Does anyone have an approach to this?

Thank you very much

PS.:

I have already tried it with implode (), but without success.

PHP code:

$arr =  array("[" . $timestamp . "000" . "," . $row['temp'] . "]");

        echo implode(", ",$arr);

Output:

[[1591072800000,12.5][1591073100000,12.6]........[1591367580000,20.7][1591367640000,20.5]]
Mi Wi
  • 1
  • 2
  • Use `json_encode` and do not invent the wheel. – u_mulder Jun 05 '20 at 14:43
  • 1
    @u_mulder reinvent* :) – Onimusha Jun 05 '20 at 14:45
  • Also note that if you're trying to time the row fetches in order to graph it, this will probably not work as is almost certainly prefetching in the background... it would probably be best to query Mysql performance metrics directly, or you might have to look into explicitly disabling optimizations - but even then you'll get even less significant data. – dagelf Jun 05 '20 at 14:54

1 Answers1

1

Why not put what you want into a proper array and then echo the json?

$output = array();
if ($result = $con->query("SELECT * FROM table")) {
    while($row = $result->fetch_array(MYSQLI_ASSOC)) {
        $output[] = array(strtotime($row['datetime']) . "000", $row['temp']);
    }
}
$result->close(); $con->close();
echo json_encode($output);`
Onimusha
  • 3,348
  • 2
  • 26
  • 32
  • +1 IMO, 99% of the times the string-concatenation operator is used in PHP scripts are against best practices. – Bill Karwin Jun 05 '20 at 15:29
  • Thanks for the answer. the comma at the end is gone. But now I have quotes that I don't need. How do I get it away? i need the output format like this: `[[1591072800000,12.5],[1591073100000,12.6],[1591367580000,20.7],[1591367640000,20.5]]` at the moment I get it like this:`[["1591072800000","12.5"],["1591073100000","12.6"],["1591367580000","20.7"],["1591367640000","20.5"]]` Does somebody has any idea? – Mi Wi Jun 05 '20 at 16:41
  • Depends what you want to use it for. Try `array((int)strtotime($row['datetime'])*1000,(float)$row['temp']);` inside the loop instead. – Onimusha Jun 05 '20 at 16:44