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  
} 

この冗長性を減らすために何ができますか?ご覧のとおり、最後のステートメントは配列とは異なる処理を行うため、関数を作成できません。ただし、ファイルの読み取り、文の分割、変数の割り当てのプロセスは同じです。

ありがとうございました

4

3 に答える 3

2

foreach($words as $word)「in」ではなく「as」を使用して入力するつもりだったと思いますが、それは質問に比べれば些細なことです。

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_maparray_walkarray_reduceにも興味があるかもしれませんが、個人的にはループよりも優れているとは感じていません...phpのforeachはかなり素晴らしいです。

于 2012-04-24T22:42:29.213 に答える