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


Php index of element in the array, update element

由于某些原因,$post总是<0. indoxOf函数工作得很好。我在其他代码上使用它,它工作得很好

由于某些原因,即使我在下一个循环中添加了像这样的元素array_push($groups, $tempDon);, I仍然返回-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;
    }

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

                $tempDom = $don;
                $tempDon->count = 1;
                array_push($groups, $tempDon);

您的else块也有类似的问题。

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

编辑

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