2013-02-10 135 views
0

我想这样回答PHP笨数据库查询

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

但是当我运行查询

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

然后,我就在最后一个额外的昏迷PLZ帮我删除此

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

回答

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

我还假设,你不想呼应城市的名字,如果它是空的,否则你会最终空""

+0

thnaks米哈尔它解决我的问题.. – 2013-02-10 08:47:26

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

此外,您还可以使用破灭()进行连结这样太:

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

可能是行不通的,因为他只想找一个属性 - 'city_name'。 – 2013-02-10 08:35:02

+0

是的,我意识到,所以为此添加了一段。传递到爆() – complex857 2013-02-10 08:36:47

+0

ivalid说法....这个错误使用此方法 – 2013-02-10 08:56:56

0

可以Concat的结果带入一个变量,最右边修剪“”。

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

感谢这个,这也可以作为米哈尔中号告诉 – 2013-02-18 04:42:03