我正在学习如何使用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
}
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
}
我该怎么做才能减少这种冗余?正如您所看到的,我无法创建函数,因为最后一个语句对数组执行了不同的操作。但是阅读文件,拆分句子和分配变量的过程是相同的
谢谢
答案 0 :(得分: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
这条线了。
答案 1 :(得分: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.
}
答案 2 :(得分: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_walk和array_reduce感兴趣,虽然我个人认为它们往往不比循环更好... php的foreach非常棒真棒