3

我正在学习如何使用 PHP。我将文件内容读入数组并为数组中的每个索引分配变量名。

例如:
$words = file("example.txt"); #each line of the file will have the format a, b, c , d

foreach ($words in $word) {  
$content = explode(",", $word); #split a, b, c, d  
list($a, $b, $c, $d) = $content;  
do something  
}  

/* And now I want to read file, split the sentence and loop over the array again, but
 the last statement will do something else different:   */
foreach ($words in $word) {  
$content = explode(",", $word); #split a, b, c, d  
list($a, $b, $c, $d) = $content;  
do something else different  
} 

我能做些什么来减少这种冗余?如您所见,我无法创建函数,因为最后一条语句对数组做了不同的事情。但是读取文件,拆分句子,分配vars的过程是一样的

谢谢

4

3 回答 3

2

我假设你打算foreach($words as $word)用“as”而不是“in”来输入,但这与问题相比只是一件小事。

您当然可以通过存储explode调用结果来减少冗余:

$lines = Array();
foreach($words as $word) {
    list($a,$b,$c,$d) = $lines[] = explode(",",$word);
    // do something here
}

foreach($lines as $line) {
    list($a,$b,$c,$d) = $line;
    // do something else
}

这样你就不必再explode排队了。

于 2012-04-24T22:20:38.623 回答
1

好吧,如果你只是打算使用 $a、$b、$c 和 $d,并且保持 $content 不变,只需再次列出 $content 来做一些不同的事情。

foreach ($words in $word) {  
  $content = explode(",", $word); #split a, b, c, d  

  list($a, $b, $c, $d) = $content;
  // do something, and when you're done:

  list($a, $b, $c, $d) = $content;
  // do something else different.
}
于 2012-04-24T22:31:47.717 回答
0

有很多变化。棘手的部分是识别可以抽象出来的通用部分。有时,您试图使代码过于通用,从而使代码变得更糟。但这里有一个使用匿名函数的示例。

function foo($filename, $func) {
    $words = file($filename);
    foreach ($words as $word) {
        $content = explode(",", $word);
        call_user_func_array($func, $content);
    }
}

foo('people.txt', function($a, $b, $c, $d) {
    echo "$a\n";
});

foo('people.txt', function($a, $b, $c, $d) {
    echo $b + $c;
});

您可能还对array_map 、array_walkarray_reduce感兴趣,尽管我个人不觉得它们通常比循环更好...... php 的 foreach 非常棒。

于 2012-04-24T22:42:29.213 回答