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
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";
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.