【问题标题】:Php index of element in the array, update element数组中元素的php索引,更新元素
【发布时间】:2011-12-23 19:29:35
【问题描述】:

由于某种原因,$post 总是

由于某种原因,即使我在下一个循环中添加了这样的元素array_push($groups, $tempDon);,我仍然继续返回 -1

$donations = $this->getInstitutionDonations($post->ID);

            $groups=array();

            foreach( $donations as $don ) : setup_postdata($don); 

                $pos = $this->indexOf($don, $groups);

                print_r($pos);

                if($pos < 0)
                {
                    $tempDom = $don;

                    $tempDon->count = 1;

                    array_push($groups, $tempDon);
                }
                else
                {
                    $tempDom = $groups[$pos];

                    $tempDon->count++;

                    array_splice($tempDon);

                    array_push($groups, $tempDon);

                    echo '<br><br><br>ahhhhhhhhhh<br><br>';
                }
            endforeach;

     protected function indexOf($needle, $haystack) {            // conversion of JavaScripts most awesome
        for ($i=0;$i<count($haystack);$i++) {         // indexOf function.  Searches an array for
                if ($haystack[$i] == $needle) {       // a value and returns the index of the *first*
                        return $i;                    // occurance
                }
        }
        return -1;
    }

【问题讨论】:

  • 好吧,也许是因为你从来没有改变过$pos的值?
  • 请不要混合使用 if / foreach 等的标准和替代语法。您的代码的可读性会增加。旁边indexOf的定义未知(需要加代码),$don是什么?
  • -1??好吧,我应该更改 $pos = $this-&gt;indexOf($don, $groups); 所以下次循环时 groups 将有一个元素,我强制元素相同......仍然不明白为什么 -1 这不公平
  • $don 是在 foreach 上指定的数组 $donations 的当前元素

标签: php arrays wordpress


【解决方案1】:

对我来说,这似乎是一个校对不佳的问题(注意 $tempDom$tempDon):

                $tempDom = $don;

                $tempDon->count = 1;

                array_push($groups, $tempDon);

您的else 块也有类似问题。

我也完全同意 @hakre 关于语法不一致的评论。

编辑

我还想建议您在 indexOf 方法的主体中使用 PHP 的内置 array_search 函数,而不是自己滚动。

【讨论】:

  • 我也同意.. 但我不是 php 程序员,只是想解决代码上的一些问题... :( 顺便说一句,我修复了校对问题,但没有任何改变。仍然没有进入其他
  • 仅仅因为您没有进入else 块并不意味着存在错误。如果$don 已经存在于$groups 数组中,您似乎只会点击else 块,这表明存在某种重复。如果您在 $donations 中没有重复项,您将无法到达 else 块。
  • 你是对的。我没有重复的元素,即使我有。非常感谢。我也在使用array_sarch()。 tkx!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-09
  • 2018-09-21
  • 2011-04-15
  • 1970-01-01
  • 1970-01-01
  • 2019-05-27
相关资源
最近更新 更多