【问题标题】:PHP array empty after pushing in foreach推入foreach后PHP数组为空
【发布时间】:2016-02-02 14:01:48
【问题描述】:

我在 foreach 循环中将值推送到数组中,并且这些值似乎已添加到数组中,因此问题不在于推送条件。但是,当我再次遍历该数组时,它是空的。

谁能给我解释一下,为什么这个代码

foreach ($allItems as $pair) {
    for ($i = 0; $i < count($keywords); $i++) {
        if ($this->itemInArray($pair["item"], $items2D[$i])) {
            array_push($pair["keywords"], $keywords[$i]->getWord());
        }
    }
    $this->log("Keywords count inside loop: ".count($pair["keywords"]));
}

foreach ($allItems as $pair) {
    $this->log("Keywords count outside loop: ".count($pair["keywords"]));
}

输出这个:

Keywords count inside loop: 3
Keywords count inside loop: 1
Keywords count inside loop: 1
Keywords count inside loop: 1
Keywords count outside loop: 0
Keywords count outside loop: 0
Keywords count outside loop: 0
Keywords count outside loop: 0

我做错了什么以及如何解决?

【问题讨论】:

    标签: php arrays foreach push is-empty


    【解决方案1】:

    通过这个你得到一个数组的副本并修改副本($pair):

    foreach ($allItems as $pair) {
    

    您需要修改以获取对$pair 的引用(注意&amp;):

    foreach ($allItems as &$pair) {
    

    【讨论】:

      【解决方案2】:

      在将项目推入其中时,您不能使用 foreach() 遍历数组。

      尝试在 foreach 语句中推入一个新变量:

      array_push($newPair,$keywords[$i]->getWord());

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-08
        • 1970-01-01
        • 2021-06-09
        • 2019-06-13
        • 2017-08-16
        • 2018-08-28
        相关资源
        最近更新 更多