2015-07-03 16 views
1

如何刪除輸出的最後一個字符(,)。從結果中刪除最後一個字符

我嘗試了幾件事,但他們都沒有爲我工作。 這是我的代碼:

$sql = "SELECT t_id, t_time, t_value FROM templogger"; 
$result = $conn->query($sql); 

if ($result->num_rows > 0) { 
    // output data of each row 
    while($row = $result->fetch_assoc()) { 
     $string = "[".$row["t_time"].", ".$row["t_value"]."],"; 
     $trim = substr($string, 0, -1); 

echo $ trim;

} 
+0

你試圖打印時間和價值就像一個JSON陣列? – rotvulpix

+0

不要立即回顯出來,建立一個更大的字符串,通過執行'substr($ string,0,-1)'去除尾隨的逗號,然後將其回顯出來。 – Andrew

回答

2

建立你的輸出,然後在刪除最後的逗號後回顯一次。

$final = ""; 
while($row = $result->fetch_assoc()) { 
    $final .= "[".$row["t_time"].", ".$row["t_value"]."],"; 
} 
$final = substr($final, 0, -1); 
echo $final; 
2

不要將它輸出到第一位。

猜解:

$first = true; 
while($row = $result->fetch_assoc()) { 
    if(!$first) { echo ','; } 
    echo "[".$row["t_time"].", ".$row["t_value"]."]"; 
} 

破滅:

$foo = []; 
while($row = $result->fetch_assoc()) { 
    $foo[] = "[".$row["t_time"].", ".$row["t_value"]."]"; 
} 
echo implode(',', $foo); 

但如果你只是想輸出JSON像@rotvulpix建議,那麼你不應該嘗試在第一手動格式化地方:

$foo = []; 
while($row = $result->fetch_assoc()) { 
    $foo[] = [ $row["t_time"], $row["t_value"] ]; 
} 
echo json_encode($foo); 
+0

這裏的一個n00b位,對JSON一無所知,我正在寫一個microtime到數據庫中。我喜歡提取日期/時間和值以將其添加到FLOT中 – Niles

+0

個人喜歡使用implode()的粉絲。對此的最優雅的解決方案,等待輸出,直到完成,無論如何是一個好方法。 +1 –

0
$total  = $result->num_rows; 
$counter = 0; 
while ($row = mysql_fetch_array($result)) { 
    echo '['.$row['t_time'].', '.$row['t_value'].']'; 
    if (++$counter !== $total) { 
     echo ','; 
    } 
} 
0

有可能是一個更好的解決方案,但是這應該做的伎倆。

替換:

while($row = $result->fetch_assoc()) { 
    echo "[".$row["t_time"].", ".$row["t_value"]."],"; 
} 

有了:

$z=0; 
while($row = $result->fetch_assoc()) { 
    $row_array[$z] = "[".$row["t_time"].", ".$row["t_value"]."]"; 
    $z++; 
} 

$z=0; 
while($z < count($row_array)) { 
    if($z == count($row_array)-1) { 
     echo $row_array[$z]; 
    } else { 
     echo $row_array[$z].',';  
    } 
    $z++; 
} 
+0

對不起,不起作用,最後還是加了一句 – Niles

相關問題