2013-02-10 139 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