terrid Posted August 13, 2010 Share Posted August 13, 2010 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] Quote Link to comment https://forums.phpfreaks.com/topic/210631-appending-char-to-an-array-using-count/ Share on other sites More sharing options...
foxsoup Posted August 13, 2010 Share Posted August 13, 2010 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"; } Quote Link to comment https://forums.phpfreaks.com/topic/210631-appending-char-to-an-array-using-count/#findComment-1098855 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.