2012-04-24 16 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 
} 

この冗長性を減らすにはどうすればよいですか?ご覧のように、最後のステートメントは配列とは何か異なるので、関数を作成することはできません。しかし、ファイル、分割文章を読んで、そしてVARSを割り当てるプロセスは同じ

ではなく、「中」の「として」と、私はあなたがforeach($words as $word)を入力するためのものと仮定していますあなたに

答えて

2

に感謝しているが、それはただのです問題と比較してマイナーなこと。

あなたは確かに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を再度リストして、別のものを実行してください。

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_walk、およびarray_reduceにintrestedてされる可能性があります... PHPのforeachのはかなりくそが素晴らしいです。