2011-11-04 187 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

相关问题