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 映射,即一个键指向一个值。所以你正在覆盖中间值,因为它也有 key 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 回答