2017-04-20 52 views
1

末印刷額外的數字我有一個PHP(訴7.0.16)腳本在命令行上運行:的printf在CLI PHP在行

$ct = 1; 
foreach($sort_this as $cur_site_id => $dx){ 

    $cur_location = $locations[$cur_site_id]['location']; 
    $msg = "\033[A\33[2K\r" . 'getting data for %25s (' . $cur_site_id . ') store: %7s %01.2f' . "\n"; 
    echo printf($msg, $cur_location, ($ct . '/' . count($sort_this)), number_format((($ct/count($sort_this)) * 100), 2)); 
    $ct++; 
} 

這個循環運行約40次迭代。 printf語句適用於1個小問題。在「獲取數據」行後面的行中,我看到一個從7x-7y開始增加的數字(有時從71開始,有時在77等)。我無法弄清楚是什麼導致這個數字被打印出來。因此,當循環開始我看到屏幕上的內容是這樣的:

getting data for     DENVER (531) store: 42/42 0.00 
77 

,並在完成時是這樣的:

getting data for     SEATTLE (784) store: 42/42 100.00 
79 

我發現如何打印在同一線路上,在這裏清除數據:

Erase the current printed console line

有沒有一種方法,以防止顯示7X代碼?另外,它們是什麼?

回答

2

的問題是在這條線:

echo printf(...) 

printf()作成使用了參數(格式和值)並將其打印的字符串。它返回打印字符的數量(它生成的字符串的長度)。

然後您的代碼將此值傳遞給打印它的echo。這是70-77範圍內額外數字的來源。

您應該刪除echo或使用sprintf()而不是printf()

sprintf()生成的字符串與printf()一樣,但不打印;它會返回它並將其作爲參數傳遞給顯示它的echo

+0

不能相信我錯過了。非常感謝! – raphael75

1

printf()返回輸出字符串的長度。

PHP docs

返回值:返回輸出字符串的長度。

剛剛刪除echo fom那行。

+0

非常好,謝謝! – raphael75