2012-04-24 150 views
2

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

例如:
$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 
} 

我能做些什么来减少这种冗余?正如你所看到的,我不能做一个函数,因为最后一条语句做了与数组不同的事情。但是,读文件,拆分句子,并指派瓦尔过程是相同的

谢谢

回答

2

我假设你想键入foreach($words as $word),以“为”而不是“中”,但是这只是一个与问题相比较小的事情。

你当然可以通过存储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行一次。

0

那么,如果你只是要使用$ 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. 
} 
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_maparray_walkarray_reduce intrested,虽然我个人不觉得吗更有往往比一个循环更好的... PHP的的foreach是相当不错的真棒。