php codeigniter数据库查询

时间:2013-02-10 08:25:12

标签: php mysql codeigniter

我想这样回答

[ “巴丁”, “Bahawalnagar”, “巴哈瓦尔布尔”]

但是当我运行查询

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

然后我在最后一次PLZ中得到了额外的昏迷,帮我解除了这个

我想删除最后一次昏迷 [ “巴丁”, “Bahawalnagar”, “巴哈瓦尔布尔”,]

4 个答案:

答案 0 :(得分: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 ']';
}

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

答案 1 :(得分: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).'"]';

答案 2 :(得分: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
}

答案 3 :(得分: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 ']';
    }