2016-04-27 187 views
1

我可以用逗號分隔連接列,但是如果在第二列是空的,如何刪除逗號? 在下面,我有2列我想加入otot2和otot3 1.如何在otot2後不顯示逗號如果otot3 null? 2.如何otot2和otot 3 null如何不顯示任何逗號? 3. otot2和otot3靈活(並不總是有數據)用逗號分隔的列

這裏我對輸出的查詢PHP代碼:

if(mysqli_num_rows($hasil) > 0) 
{ 
    $response = array(); 
    while($data = mysqli_fetch_array($hasil)) 
    { 
     $h['main muscle'] = $data['otot1']; 
     $h['other muscle'] = $data['otot2'].', '.$data['otot3']; 

     array_push($response, $h); 
    } 
    $response["success"]; 
    echo json_encode($response); 
+0

如果(ISNULL($數據[ 'otot3']))其他.. – 2016-04-27 06:05:11

+0

@Dagon您能不能給一個完整的代碼? –

回答

1

一個簡單的解決辦法是 -

$response = array(); 
while($data = mysqli_fetch_array($hasil)) 
{ 
    // other code 

    $temp = array($data['otot2'], $data['otot3']); // Store them in array 
    $temp = array_filter($temp); // remove empty values 
    $h['other muscle'] = implode(',', $temp); // implode them with (,) 

    // Other codes 

    array_push($response, $h); 
} 

通過使用array_filter & implode您不必擔心,,因爲array_filter會刪除空值,並且如果有第值e數組他們的字符串將會是,,否則不會。

或者你也可以嘗試這個

$h['other muscle'] = $data['otot2']; 
if($data['otot3'] !== null) 
    $h['other muscle'] .= ', ' . $data['otot3']; // Concatenate 

Demo

+0

感謝您的幫助,即時通訊嘗試,如果otot3 null,otot2 stil用逗號顯示 –

+0

是的即時嘗試你的代碼,但逗號仍然顯示後otot2當otot3 null,和otot2和otot3 null逗號仍然顯示 –

+0

@F_X它應該不。檢查演示。你已經實現了哪些代碼。 –