dongma6326 2013-12-24 02:46
浏览 56
已采纳

php foreach迭代对象属性数组不递增值

Please help! I have been staring at this for too long. I have a property of an object that is an array of objects. I want to pass in an object to a method of the parent object and search through that array property for a match, and if one is found return the index. Otherwise, I need it to return -1. For some reason, it is not iterating. If I echo out what should be the $order->product property (where the index is pointing during the loop), it is unchanging. I have dumped the array and I know it contains different values. I can show you a big var dump, but I figured I would first ask if there is a simple error or something else that is obvious to you that I have missed.

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;
    } 
  }

If anyone has any ideas, I am open to discuss and post more information as needed. Thank you for your time.

  • 写回答

1条回答 默认 最新

  • doukongyong44772 2013-12-24 02:50
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 MATLAB联合adams仿真卡死如何解决(代码模型无问题)
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改