1

preg_match の結果を別の配列にプッシュしようとすると、中央の値が欠落している理由を説明してください。それはばかげたことか、私の理解の大きなギャップです。いずれにせよ、助けが必要です。これが私のコードです:

<?php 

$text = 'The group, which gathered at the Somerfield depot in Bridgwater, Somerset, 
        on Thursday night, complain that consumers believe foreign meat which has been 
        processed in the UK is British because of inadequate labelling.';

$word = 'the';

preg_match_all("/\b" . $word . "\b/i", $text, $matches, PREG_OFFSET_CAPTURE);

$word_pos = array();


for($i = 0; $i < sizeof($matches[0]); $i++){

    $word_pos[$matches[0][$i][0]] = $matches[0][$i][1];

}



    echo "<pre>";
    print_r($matches);
    echo "</pre>";

    echo "<pre>";
    print_r($word_pos);
    echo "</pre>";

?>

私はこの出力を得ます:

Array
(
[0] => Array
    (
        [0] => Array
            (
                [0] => The
                [1] => 0
            )

        [1] => Array
            (
                [0] => the
                [1] => 29
            )

        [2] => Array
            (
                [0] => the
                [1] => 177
            )

    )

)
Array
(
[The] => 0
[the] => 177
)

問題は、[the] => 29 がないのはなぜですか? より良い方法はありますか?ありがとう。

4

3 に答える 3

1

PHP配列は1:1のマッピングです。つまり、1つのキーが正確に1つの値を指します。つまり、キーもあるため、中央の値を上書きしていますthe

最も簡単な解決策は、オフセットをキーとして使用し、一致した文字列を値として使用することです。ただし、結果をどのように処理するかによっては、完全に異なる構造の方が適切な場合があります。

于 2012-09-07T22:21:47.940 に答える
1

最初に割り当て$word_pos["the"] = 29てから、で上書きし$word_pos["the"] = 177ます。

Theインデックスでは大文字と小文字が区別されるため、上書きしません。

したがって、次のようなオブジェクトの配列を使用する可能性があります。

$object = new stdClass;
$object->word = "the"; // for example
$object->pos = 29; // example :)

配列に割り当てます

$positions = array(); // just init once
$positions[] = $object;

または、オブジェクトの代わりに連想配列を割り当てることができるので、次のようになります。

$object = array(
    'word' => 'the',
    'pos' => 29
);

または、自分のやり方を割り当てますが、上書きする代わりに、次のように配列に追加するだけです。

$word_pos[$matches[0][$i][0]][] = $matches[0][$i][1];

それ以外の

$word_pos[$matches[0][$i][0]] = $matches[0][$i][1];

したがって、次のようなものが得られます。

Array
(
[The] => Array
      (
         [0] => 0
      )
[the] => Array
      (
         [0] => 29
         [1] => 177
      )
)

お役に立てば幸いです:)

于 2012-09-07T22:22:48.990 に答える
1

実際に起こっていること:

when i=0,
$word_pos[The] = 0   //mathches[0][0][0]=The 
when i=1
$word_pos[the] = 29       
when i=3
$word_pos[the] = 177  //here this "the" key overrides the previous one
                      //so your middle 'the' is going to lost :(

配列ベースのソリューションは次のようになります。

for($i = 0; $i < sizeof($matches[0]); $i++){

    if (array_key_exists ( $matches[0][$i][0] , $word_pos ) ) {

        $word_pos[$matches[0][$i][0]] [] = $matches[0][$i][1];

    }

    else $word_pos[$matches[0][$i][0]] = array ( $matches[0][$i][1] );

}

$word_pos をダンプすると、出力は次のようになります。

Array
(
[The] => Array
    (
    [0] => 0
        )
    [the] => Array 
        (
             [0] => 29 ,
             [1] => 177
        )
    )

それが役立つことを願っています。

参考:array_key_exist

于 2012-09-07T22:46:14.603 に答える