0

请帮忙!我已经盯着这个太久了。我有一个对象的属性,它是一个对象数组。我想将一个对象传递给父对象的方法,并在该数组属性中搜索匹配项,如果找到则返回索引。否则,我需要它返回-1。由于某种原因,它没有迭代。如果我回显应该是 $order->product 属性(循环期间索引指向的位置),它是不变的。我已经转储了数组,我知道它包含不同的值。我可以向您展示一个大的 var 转储,但我想我会先询问是否有一个简单的错误或其他对您来说很明显但我错过的东西。

public function getItemIndex($prod) {
    if (isset($this->orders)){
      foreach($this->orders as $key => $order) {
        if ($order->product == $prod) { //if I echo this $order->product to the screen, it is unchanging
          return $key;
        } else { return -1; }
      }
    }
    else {
      return -1;
    } 
  }

如果有人有任何想法,我愿意讨论并根据需要发布更多信息。感谢您的时间。

4

1 回答 1

5

You are ALWAYS returning a value on the first iteration, either the $key or -1. Try removing the else statement that you currently have. This will allow you to fully iterate over the entire array.

public function getItemIndex($prod) {
    if (isset($this->orders)){
        foreach($this->orders as $key => $order) {
            if ($order->product == $prod) { //if I echo this $order->product to the screen, it is unchanging
                return $key;
            }
        }
    }

    return -1;
}

This will ONLY return -1 once it has iterated over everything and found nothing to match. It will still return $key if it finds a match.

于 2013-12-24T02:50:49.970 回答