数组中元素的Php索引,更新元素

时间:2011-12-23 19:29:36

标签: php arrays wordpress

由于某种原因$post总是< 0. indoxOf功能很好用。我在ohter代码上使用它并且效果很好

由于某种原因,即使我在下一个循环中添加了像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;
    }

1 个答案:

答案 0 :(得分:1)

这看起来像是一个校对不良的问题(注意 $ tempDom vs $ tempDon ):

                $tempDom = $don;

                $tempDon->count = 1;

                array_push($groups, $tempDon);

您的else区块也存在类似问题。

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

编辑

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