PHP:为什么在关联数组中缺少值


PHP: Why missing values in associative array?

当我试图将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?有更好的方法吗?谢谢

PHP数组是1:1映射,即一个键指向一个值。因此,您正在覆盖中间值,因为它还有关键字the

最简单的解决方案是使用偏移量作为键,使用匹配的字符串作为值。然而,根据你想对结果做什么,一个完全不同的结构可能更合适。

首先分配$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
      )
)

希望能有所帮助:)

实际发生的情况:

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