JSON_Encode or Remove Last Comma

Json_encode or remove last comma?

At the risk of answering without a clear question, just build an array of what you want and encode it:

foreach ($data as $record) {
$array[] = array($record['timestamp'], $record['swell']['absMinBreakingHeight']);
}
echo json_encode($array);

Removing Last Comma in JSON output list

Use Below code it will work for you.

$urls_actors = amy_movie_get_movie_taxomony3( $post->ID, 'amy_actor' );
$urls_actors = explode("," ,$urls_actors);

$actors_name = amy_movie_get_movie_taxomony2( $post->ID, 'amy_actor' );
$actors_name = explode("," ,$actors_name);

foreach ($actors_name as $key => $actor) {
$actors_list[] = '
{
"@type": "Person",
"name": "'.$actor.'",
"url": "'.$urls_actors[$key].'",
"sameAs": "'.$urls_actors[$key].'"
}';
}

<script type="application/ld+json">

"actor": [
<?php echo implode(',',$actors_list);?>],

</script>

I just take values in array and at last. I implode it with ","

removing last comma in php from an echo string with json output

This is not the way to generate a JSON.

Create an array and use json_encode() function to convert it into a JSON string.

But if you insist on doing this your way:

$json = Array();
foreach($enquirydates as $edate) {
if($x <= $firstunixdate) { //first follow-up
$json[] = '{"date":"'.date("Y-m-d", $firstunixdate).'","type":"Follow-up","title":"Student Enquiry Follow-up (First Follow-Up)","description":"First Student Enquiry followup due..","url":"http://test.com/admin/followup.php?time='.$unixenquirydate.'"}';
}
else if($x <= $secondunixdate) { //second followup
$json[] = '{"date":"'.date("Y-m-d",$secondunixdate).'","type":"Follow-up","title":"Student Enquiry Follow-up (Second Follow-Up)","description":"Second Student Enquiry followup due..","url":"http://test.com/admin/followup.php?time='.$unixenquirydate.'"}';
}
else if($x > $finalunixdate) { //enquiry open for more than 25 days
$json[] = '{"date":"'.date("Y-m-d",$x).'","type":"Follow-up","title":"Student Enquiry open for more than 25 days","description":"Second Student Enquiry followup due..","url":"http://test.com/admin/followup.php?time='.$unixenquirydate.'"}';
} //end if
}
echo '['.implode(',', $json).']';

Json_Encode php last comma

Let json_encode handle the entire thing - build one array of data, and use json_encode on that.

$result = mysqli_query($mysqli, "SELECT * FROM `csvdata`");

$response = array();
$response['films'] = array();

while ($row = mysqli_fetch_array($result)) {
$response['films'][] = $row;
}

echo json_encode($response);

Remove commas from json_encode

If you want to remove commas then why are you using json_encode()?

After comma removal the strings cannot be decoded anymore. Use a different encoding, for example, join the values using a separator:

$piden = implode('/', $_POST['piden']);

However, even this way you may have issues when the input data contains commas. Most probably you are "encoding" the CSV by hand and fail to properly quote the values that contain the separator (commas f.e).

The PHP function fputcsv() can do all the hard work for you when it comes to export data as CSV.

How to remove comma from this json object?

Do like this

$result=mysql_query($sql);
$jsonResult = '{"results" : [ ';
$i=0;
while ($data=mysql_fetch_assoc($result)) {
if($i != 0){
$jsonResult .=',';
}
$jsonResult .=json_encode($data);
i++;
}
$jsonResult .= ']}';

Removing Last Comma within while loop - PHP

I like to follow best practice whereever possible, but in this particular instance I needed to deviate from best practice due to some environment restrictions I had. I thought I'd share the solution I ended up using, regardless of it being overly complicated.

$sth = mysql_query("SELECT name,address,address2,city,state,postal,phone,lat,lng FROM mapdata");
$num_rows = mysql_num_rows($sth);
$counter = 0;
echo '[';
while($r = mysql_fetch_assoc($sth)) {
if (++$counter == $num_rows) {
echo preg_replace("/^,/",'',str_replace(',}','}',json_encode($r)));

}
else {
echo preg_replace("/^,/",'',str_replace(',}','}',json_encode($r)) . ',');
}
}
echo "]";
mysql_close($connection);

Remove the last comma of a JSON file and PHP

Get the query row count and create a counter to know what row you are iterating in the loop, only add the comma if the counter is different the total rows:

  {
"data": [
<?php
require_once("../../config.php");
$qtodos = $mysqli->query("SELECT * FROM negocios");
$TotalRcount = $qtodos->num_rows; // <<<< row count
$counter = 0;

while($todos = $qtodos -> fetch_assoc()) { $counter++ // <<<< add the counter
?>
{
"id": <?php echo $todos['idnegocios']; ?>,
"category": "real_estate",
"title": "<?php echo $todos['nombre']; ?>",
"location": "<?php echo $todos['direccion']; ?>",
"latitude": 51.541599,
"longitude": -0.112588,
"url": "item-detail.html",
"type": "Apartment",
"type_icon": "assets/icons/store/apparel/umbrella-2.png",
"rating": 4,
"gallery":
[
"assets/img/items/1.jpg",
"assets/img/items/5.jpg",
"assets/img/items/4.jpg"
],
"features":
[
"Free Parking",
"Cards Accepted",
"Wi-Fi",
"Air Condition",
"Reservations",
"Teambuildings",
"Places to seat"
],
"date_created": "2014-11-03",
"price": "$2500",
"featured": 0,
"color": "",
"person_id": 1,
"year": 1980,
"special_offer": 0,
"item_specific":
{
"bedrooms": 4,
"bathrooms": 2,
"rooms": 4,
"garages": 1,
"area": 240
},
"description": "asasasas odio nibh, luctus non pulvinar a, ultricies ac diam. Donec neque massa, viverra interdum eros ut, imperdiet pellentesque mauris. Proin sit amet scelerisque risus. Donec semper semper erat ut mollis. Curabitur suscipit, justo eu dignissim lacinia, ante sapien pharetra duin consectetur eros augue sed ex. Donec a odio rutrum, hendrerit sapien vitae, euismod arcu.",
"last_review": "Curabitur odio nibh, luctus non pulvinar a, ultricies ac diam. Donec neque massa, viverra interdum eros ut, imperdiet",
"last_review_rating": 5
}<?php
if($TotalRcount != $counter)
{ echo ','}; // <<<< only add the comma when the counter is different than total rows
}
?>
]
}

Add comma from print json_encode

What you actually need to do is produce an array of results, which you can do by pushing values into an array in the loop, and then json_encode the array after the loop:

$print = array();
foreach($resultdata as $data){
$print[]= array(
"id" => $data['id'],
"username" => $data['username'],
"text" => $data['text']
);
}
print json_encode($print);


Related Topics



Leave a reply



Submit