2015-11-02 103 views
3
$sql=" SELECT * from `request_location` where requestid = '".$requestid."' "; 
    $result = mysqli_query($con, $sql); 
    if(mysqli_num_rows($result)>0) 
     { 
      echo "("; 
      while($row = mysqli_fetch_assoc($result)) 
       { 
        echo $row["location_tag"]; 
        echo ","; 
       } 
      echo ")"; 
     } 

我有在將結果放在圓括號內的格式顯示數據,並且每個項由逗號顯示數據

結果是我得到是分離這上面的代碼這樣

(a,b,c,) 

雖然這似乎是罰款,但我想,因爲它是這樣

(a,b,c) 
最後一項逗號應該不是C後出現210

誰能告訴如何在最後一個元素之後刪除逗號

回答

1

解決方案1:

可以使用implode()功能和數組做()。

背後的邏輯:

1)取一個空白數組。

2)獲取的結果的方式相同的現有。

3)追加結果到陣列。

4)在循環結束之後implode()用逗號陣列。

5)添加預先考慮,並張貼未決()到結果中。

sql=" SELECT * from `request_location` where requestid = '".$requestid."' "; 
$result = mysqli_query($con, $sql); 
$arr = array(); 
if(mysqli_num_rows($result)>0) { 
    while($row = mysqli_fetch_assoc($result)) { 
    $arr[] = ["location_tag"]; 
    } 
} 
echo ! empty($arr) ? '(' . implode(',', $arr) . ')' : ''; 

解決方案2:

使用MySQL的GROUP_CONCAT()(如果你想獲取從數據庫表只有一個字段)。

sql=" SELECT GROUP_CONCAT(location_tag) from `request_location` where requestid = '".$requestid."' "; 
    $result = mysqli_query($con, $sql); 
    $ids = ''; 
    if(mysqli_num_rows($result)>0) { 
     while($row = mysqli_fetch_assoc($result)) { 
     $ids = ["location_tag"]; 
     } 
    } 

echo ! empty($ids) ? '(' . $ids . ')' : ''; 
+0

implode正在刪除所有逗號而我想刪除只是最後一個 – pp1989

+0

implode()函數將數組元素連接到一個字符串。所以,它應該有兩個數組元素之間的逗號(傳遞參數)。請再次檢查代碼。 – Pupil

2

試試這個使用PHP str_replace: -

$str='(a,b,c,)'; 
str_replace(",)",")",$str); 

Demo

或試試這個代碼: -

$var= "("; 
while($row = mysqli_fetch_assoc($result)) 
{ 
$var.= $row["location_tag"]; 
$var.= ","; 
} 
$var.= ")"; 
echo str_replace(",)",")",$var); 
0

使用一個IF條件和檢查兩個字符串之間的num_of_rows

$sql=" SELECT * from `request_location` where requestid = '".$requestid."' "; 
$result = mysqli_query($con, $sql); 
$count = mysqli_num_rows($result); 
if($count>0) 
    { 
     echo "("; 
     $i = 1; 
     while($row = mysqli_fetch_assoc($result)) 
      { 
       echo $row["location_tag"]; 
       if($i<$count) { 
       echo ","; 
       } 
       $i++; 

      } 
     echo ")"; 
    } 
0

這個怎麼

$sql= "SELECT * from request_location where requestid = '$requestid'"; 
$result = mysqli_query($con, $sql); 
if(mysqli_num_rows($result)>0) 
    { 
     $new = '' 
     while($row = mysqli_fetch_assoc($result)) 
     { 
      $new .= $row["location_tag"].","; 
     }    

     $data = "(".$new.")"; // Output - (a,b,c,) 
     $new_data = str_replace(",)", ")", $data); 
     echo $new_data ; // Output - (a,b,c) 

    } 
+0

@ pp1989檢查此 –

0

對於加入 「」 你可以用implode(",", array_variable),如下圖所示:

$sql=" SELECT * from `request_location` where requestid = '".$requestid."' "; 
$result = mysqli_query($con, $sql); 
if(mysqli_num_rows($result)>0) 
    { 
     while($row = mysqli_fetch_assoc($result)) 
      { 
       $location_tag_arr[] = $row["location_tag"]; 
      } 
     echo ")"; 
    } 

echo "(" . implode(",", $location_tag_arr) . ")"; 
//^output will be: (a,b,c)