phpmysqljsoncodeigniterresultset

How to create a valid JSON string from a single column of data from a CodeIgniter query result set


I want to build a string like this: ["Badin","Bahawalnagar","Bahawalpur"]

but when I run my script I get an extra comma in the last iteration.

if ($result->num_rows() > 0)
{   
    echo '[';
    foreach($result->result() as $listing)
    {
        echo '"'.$listing->city_name.'"';
        if ($listing->city_name!='')
        {
            echo ',';
        }
    }
    echo ']';
}

I want to remove the last comma inside the closing brace.

["Badin","Bahawalnagar","Bahawalpur",]


Solution

  • You code should look like this:

    if ($result->num_rows() > 0)
    {   
        echo '[';
    
        foreach($result->result() as $key => $listing)
        {
            $row = $key+1;
    
            if ($listing->city_name != '')
            {
                echo '"'.$listing->city_name.'"';
    
                // If it's not last item, then add a comma
                if ($row < $result->num_rows())
                {
                    echo ',';
                }
            }
        }
        echo ']';
    }
    

    I assumed also, that you don't want to echo the city name if it's empty, otherwise you'd end up with empty "".