2011-11-04 182 views
0
$file = fopen("test.txt","r"); 
while($line = fgets($file)) { 
    $line = trim($line); 
    list($model,$price) = preg_split('/\s+/',$line); 
    if(empty($price)) { 
    $price = 0; 
    } 
    $sql = "UPDATE products 
      SET products_price=$price 
      WHERE products_model='$model'";  
    // run the sql query. 
} 
fclose($file); 

txt文件是這樣的:代碼含義是什麼?

model price 
LB2117 19.49 
LB2381 25.99 

1,什麼是的list($model,$price) = preg_split('/\s+/',$line); 我知道preg_splitexplode的意思,但我不知道what't上述線路的參數含義 2 ,如何跳過第一條記錄。

回答

1

它將preg_split的結果分配給變量$model$price。您正在查看解析算法。對不起,如果這是不夠的。我很難理解這個問題。

此外,如果我正確讀取了這些內容,則不需要跳過第1行,除非您在數據庫中將模型定義爲「模型」。

但是,如果你想爲某些原因,你可以添加一個計數器...

$i = 0; 
while($line = fgets($file)) { 
    if($i > 0) 
    { 
    $line = trim($line); 
    list($model,$price) = preg_split('/\s+/',$line); 
    if(empty($price)) { 
     $price = 0; 
    } 
    $sql = "UPDATE products 
      SET products_price=$price 
      WHERE products_model='$model'";  
    // run the sql query. 
    } 
    $i++; 
} 
+0

但是當我運行的代碼它顯示了一個錯誤,請注意:未定義抵消: 1在第11行的D:\ www \ update.php中。第11行是列表($ model,$ price)= preg_split('/ \ s + /',$ line); – dreamchaser

1

這是一個語言結構,可以讓你在一次分配給多個變量。你可以把它看作數組拆包(preg_split返回一個數組)。所以,當你這樣做:

<?php 
list($a, $b) = explode(".","a.b"); 
echo $a . "\n"; 
echo $b . "\n"; 

您將獲得:

a 
b 

具有示於表更少元件比陣列是確定的,在陣列多餘的元素將被忽略,但在陣列,具有insufficent元素會給你一個未定義的索引錯誤。例如:

list($a) = explode(".","a.b"); // ok 
list($a,$b,$c) = explode(".","a.b") // error 
0

我不知道你指的是通過跳過第一個記錄,但...

$file = fopen("test.txt","r"); // open file for reading 
$first = true; 
while($line = fgets($file)) { // get the content file 
    if ($first === true) { $first = false;}//skip the first record 
    else{ 
    $line = trim($line);   // remove the whitespace before and after the test 
           // not in the middle 
    list($model,$price) = preg_split('/\s+/',$line); // create two variable model and price, the values are from the preg_split \s means whitespace, tab and linebreak 
    if(empty($price)) {   // if $price is empty price =0 
    $price = 0; 
    } 
    $sql = "UPDATE products  // sql update 
      SET products_price=$price 
      WHERE products_model='$model'";  
    // run the sql query. 
    } 
} 
fclose($file);     //close the file 
+0

但是當我運行代碼時,它顯示一個錯誤,注意:第11行D:\ www \ update.php中的未定義偏移量:1行11是列表($ model,$ price)= preg_split('/ \ s + /」,$線); – dreamchaser

相關問題