3

I have a JSON file with PHP, and I want to remove the last comma, because it causes an error. The code is the following:

{
"data": [
<?php
    require_once("../../config.php");
    $qtodos = $mysqli->query("SELECT * FROM negocios");
    while($todos = $qtodos -> fetch_assoc()) {
        ?>
        {
            "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
}
?>
    ]
}

I tried lots of solutions but never works in this code. I don't know when it is the last itineration of the loop, and can't remove it.

Sergio
  • 191
  • 9
  • http://stackoverflow.com/questions/3120398/php-how-to-remove-any-last-commas – MaggsWeb Jul 09 '15 at 14:17
  • 1
    @Sergio Why not first simply fill the php-array in a loop, and then use the json_encode to out? It will be more ideologically correct. – stdob-- Jul 09 '15 at 14:24
  • @stdob's answer is the only sensible one here – Rob G Jul 09 '15 at 14:25
  • @Sergio In fact, your goal is not to remove the comma. Your goal in a correct formulation of the problem, which will avoid unnecessary and wrong actions. And finally learn how to develop software. Ask yourself - I really need to delete a comma, or do I need to get the data in the cycle, fill the structure of the data and convert it to another format? – stdob-- Jul 09 '15 at 14:34

4 Answers4

1

Many possible ways. I just pick one....
remove the trailing, literal comma and change the script like so

$first = true;
while($todos = $qtodos -> fetch_assoc()) {
    if ($first) {
        $first = false;
    }
    else {
        echo ',';
    }
?>
        {
            "id":

i.e. the script doesn't print a comma after a record but before the next record.

VolkerK
  • 95,432
  • 20
  • 163
  • 226
1

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
    }
    ?>
        ]
    }
KAD
  • 10,972
  • 4
  • 31
  • 73
0

You can add a count and match the count to the total rows so when it gets to the last record it wont echo the comma

{
"data": [
<?php
    require_once("../../config.php");
    $qtodos = $mysqli->query("SELECT * FROM negocios");
    $count = 1;
    while($todos = $qtodos -> fetch_assoc()) {
        ?>
        {
            "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 ((int)$qtodos->num_rows != $count)
        echo ',';
    $count++;
}
?>
    ]
}
Danny Broadbent
  • 1,199
  • 1
  • 9
  • 21
-2
Hope, this will work 
`{
"data": [
<?php
    require_once("../../config.php");
    $qtodos = $mysqli->query("SELECT * FROM negocios");
    $count = 0;
    while($todos = $qtodos -> fetch_assoc()) {
        ?>
        {
            "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
        }
    if($count != mysql_num_rows($todos))
    {
        ,
    }
    $count += 1;
<?php
}
?>
    ]
}`
Shahbaz
  • 73
  • 8
  • 1
    Your using mysql_num_rows this is deprecated and Sergio is using mysqli class. Also why use $count+=1; when you can simply do $count++; – Danny Broadbent Jul 09 '15 at 14:24