-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?

2
  • 4
    I recommend not building JSON strings by hand. Instead, populate an array and use json_encode() Commented Jun 5, 2017 at 23:12
  • what @Phil says. If you really want to concat data like that to s string rather use implode() with an array. (for any other usecase. just as a hint for the future) Commented Jun 5, 2017 at 23:15

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

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?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.