php foreach循环冗余

php foreach循环冗余,php,function,redundancy,Php,Function,Redundancy,我正在学习如何使用PHP。我将文件内容读入数组,并为数组中的每个索引分配变量名 例如: $words=file(“example.txt”)#文件的每一行的格式为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 re

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

例如:

$words=file(“example.txt”)#文件的每一行的格式为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  
} 
我可以做些什么来减少这种冗余?如您所见,我无法生成函数,因为最后一条语句对数组做了一些不同的操作。但读取文件、拆分句子和分配变量的过程是相同的


谢谢

我想你是想在foreach($words)中键入
,用“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
}

这样,您就不必再次分解该行。

好吧,如果您只需要使用$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.
}

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

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;
});
你也可能对它感兴趣,尽管我个人不觉得它们通常比一个循环好。。。php的foreach非常棒