-1

When building a JSON string from a php for loop from an SQL query there is an unnessary comma at the end of the build string. How do I control the final comma.

$count =  label::grabAll()->count();

echo '{"data": { "graph": {';

for ($x = 0; $x < $count; $x++){

if($x <= 3){
    $cm = ',';
}else{
    $cm .= '';
}

    echo '"'.$x.'": "'.label::grabAll()->results()[$x]->count.'"'.$cm;

}

I get this result from the code above. enter image description here

How do I remove the final comma?

Blackspade
  • 45
  • 1
  • 5
  • 4
    I recommend **not** building JSON strings by hand. Instead, populate an array and use `json_encode()` – Phil Jun 05 '17 at 23:12
  • what @Phil says. If you really want to concat data like that to s string rather use [implode()](http://php.net/manual/en/function.implode.php) with an array. (for any other usecase. just as a hint for the future) – Jeff Jun 05 '17 at 23:15

2 Answers2

1

Use plain old objects / arrays and use json_encode. For example

$graph = array_map(function($result) {
    return $result->count;
}, label::graball()->results());

echo json_encode(['data' => ['graph' => $graph]]);

Demo ~ https://eval.in/812302

Phil
  • 157,677
  • 23
  • 242
  • 245
0
$count =  label::graball()->count();

$arr = array();

for ($x = 0; $x < $count; $x++){

 array_push($arr, label::graball()->results()[$x]->count);

}


echo json_encode($arr);

Thanks everyone for the quick responses. This works.

Blackspade
  • 45
  • 1
  • 5
  • Are you sure that executing `label::graball()` and `label::graball()->results()` multiple times is the correct thing to do? Is each execution querying your data source? – Phil Jun 05 '17 at 23:31