Jump to content

appending char to an array using count()


terrid

Recommended Posts

Hi all

 

I am trying to loop through an array and output as JSON.

What I'm looking to do is create something like:

 

  "something": [
{"title":"Test 1"},
{"title":"Test 2"}
],

 

Notice that the final row has no comma.

 

My code is as follows:

 

<?php foreach($something as $thing): ?>
<?php $something_array = array('title'=>$thingt->getId()); ?>
<?php echo json_encode($something_array).','."\n"; ?>
<?php endforeach; ?>

 

I had to add a comma to the end of the array, or the JSON rows would not be ended with one.

 

How can I get it so that, no matter how many items are in the array, the last row, wil not have the comma at the end?

 

With the comma at the end, my JSON doesn't validate

 

Thanks

 

 

[/code]

Link to comment
https://forums.phpfreaks.com/topic/210631-appending-char-to-an-array-using-count/
Share on other sites

Not tested this code, but using count() to get the size of the array and then having an incremental counter to determine the last array entry could work:

 

$array_size = count($something);
$count = 0;
foreach ($something as $thing) {
$count++;
$something_array = array('title' => $thing->getId());
echo json_encode($something_array);
echo ($i == $array_size) ? '' : ',';
echo "\n";
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.