2015-11-02 110 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)