0

我想这样回答

[“巴丁”,“巴哈瓦尔纳加尔”,“巴哈瓦尔普尔”]

但是当我运行查询时

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

然后我在最后一次昏迷了请帮我删除这个

我想删除最后的昏迷 ["Badin","Bahawalnagar","Bahawalpur",]

4

4 回答 4

1

您的代码应如下所示:

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 ']';
}

我还假设,如果城市名称为空,您不想回显城市名称,否则您最终会得到 empty ""

于 2013-02-10T08:31:11.293 回答
1

您的输出与 json 可疑地相似,一旦您获得城市名称,也许直接 json_encode() 就足够了:

$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);

此外,您也可以使用 implode() 进行这样的连接:

echo '["'.implode('","', $cities).'"]';
于 2013-02-10T08:33:47.797 回答
1

您可以使用 json_encode 来执行此操作

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
}
于 2013-02-18T04:36:56.863 回答
0

您可以将结果连接到变量中并修剪最右边的“,”。

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 ']';
    }
于 2013-02-10T13:20:23.863 回答