0

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",]

5 Answers 5

1

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 "".

Sign up to request clarification or add additional context in comments.

Comments

1

Your output suspiciously similar to json, maybe a straight json_encode() is enough once you get the city names:

$cities = array();
foreach($result->result() as $listing) {
   $cities = $listing->city_name;
}
$cities = array_values(array_filter($cities)); // removes the empty ones, reset the indexes


echo json_encode($cities);

Also, you could use implode() for concatenation like this too:

echo '["'.implode('","', $cities).'"]';

3 Comments

Probably wouldn't work since he's only looking for one property - city_name.
Yup, i've realized, so added a paragraph for that.
@AzamAlvi, sounds like a mistyped variable, you still need the firs snippet's $cities variable and foreach part, only the last json_encode() would be replaced by the implode one.
1

You can use json_encode to do this

if($result->num_rows > 0){
  foreach ($result->result_array() as $row){


    $new_row['label']=htmlentities(stripslashes($row['user_name']));
     $new_row['val']=htmlentities(stripslashes($row['user_id']));

    $row_set[] = $new_row; //build an array
  }
  echo json_encode($row_set); //format the array into json data
}

Comments

0

you can concat your results into a variable and trim rightmost ",".

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

    $my_result = rtrim($my_result , ",");

    echo $my_result;
        echo ']';
    }

Comments

0

Your requirements are simple: isolate a single column from the result set which might be empty and create a json-encoded flat array.

return json_encode(array_column($result->result(), 'city_name'));

Extra notes:

  1. Do not bother calling num_rows() -- it is irrelevant, just return an empty encoded array if that represents the data is in the result set.
  2. Do not call string manipulating functions before calling json_encode() unless you have a specific challenge to overcome. Keep the data pure. Definitely don't call htmlentities() or stripslashes() before encoding; if those calls are necessary, do it after decoding.
  3. If your query might return empty values in that column, wrap = array_filter() around the array_column() call before json encoding. Ideally, your SQL would be using a WHERE condition to filter out empty values.
  4. Your model (which is where I hope your script lives) should never be echoing anything, it should return its data payload to the call site.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.