PHP 将后续数组元素与前一个数组元素进行比较


PHP compare subsequent array element to previous

所以我在让一些代码工作时遇到了麻烦。基本上我想做的是:

在 foreach 循环中,如果设置了给定的数组值,请将该现有值与当前循环值进行比较,如果现有值已大于当前值,则设置现有值 = 当前值(对于迭代)。这是我正在使用的代码:

if ($usedebayxml->ack == 'Success') {
    foreach($usedebayxml->searchResult->item as $key => $value) {
        if(isset($newarray[1]['TotalCost'])) {
            if($newarray[1]['TotalCost'] > ((integer)$value->shippingInfo->shippingServiceCost + (integer)$value->sellingStatus->currentPrice)) {
                $newarray[1]['Title'] = (string)$value->title ;
                $newarray[1]['ShippingCost'] = (integer)$value->shippingInfo->shippingServiceCost;
                $newarray[1]['Price'] = (integer)$value->sellingStatus->currentPrice;
                $newarray[1]['Condition'] = 'New';
                $newarray[1]['TotalCost'] = (integer)$value->shippingInfo->shippingServiceCost + (integer)$value->sellingStatus->currentPrice;
            }
        }
        else
            $newarray[1]['Title'] = (string)$value->title;
            $newarray[1]['ShippingCost'] = (integer)$value->shippingInfo->shippingServiceCost;
            $newarray[1]['Price'] = (integer)$value->sellingStatus->currentPrice;
            $newarray[1]['Condition'] = 'Used';
            $newarray[1]['TotalCost'] = (integer)$value->shippingInfo->shippingServiceCost + (integer)$value->sellingStatus->currentPrice;
    }
}

使用此代码,最终返回的是 xml 文件中 LAST 键对象中的值(如果有帮助,则使用 simpleXML)。换句话说,我不认为第一个 if 块(如果 isset)被输入,并且值被设置为当前迭代的任何值。有人能在这里看到我的逻辑有任何缺陷吗?我已经被这个难倒了一段时间了。

我是个至高无上的白痴。这里的逻辑很好,我只是缺少一个 { 用于打开 else 块。添加此代码后,这段代码将按预期工作:)

我很惊讶,虽然我没有这个就没有抛出任何错误......我认为这可能会让我在确定为什么它最初不起作用时感到困惑。