duanlan3598 2016-12-12 15:26
浏览 24
已采纳

比较对象集合中的对象类型属性

I have the following $input :

elements: array:2 [
    0 => Tournament { 
        id: 1
        amountStaking: Price { 
            value: 2500
            currency: "EUR"
        }
    }
    1 => Tournament { 
        id: 2
        amountStaking: Price { 
            value: 2500
            currency: "EUR"
        }
    }
]

What I want to achieve is a function that will return an object or false depending of the "equality" of the $amountStaking property of each Tournament. In the previous input, it should return the "common" Price object :

Price { 
    value: 2500
    currency: "EUR"
}

But if one of the $currency value is "USD" for example, it should return false.

  • 写回答

1条回答 默认 最新

  • dtt5830659 2016-12-12 15:42
    关注
    $last = null;
    foreach ($elements as $e) {
      if ($last === null) {
        $last = e->amountStaking;
        continue;
      }
      if ($last->value != $e->value || $last->currence != $e->currency) {
        return false;
      }
      $last = e->amountStaking;
    }
    
    return $last;
    

    You walk through the array until one entry does not match the previous one. You return false immediately. If it runs through just return the last object.

    Maybe you should

    return clone $last;
    

    to make it a new object, in case you want to modify it later.


    As requested "Price agnostic":

    $last = null;
    foreach ($elements as $e) {
      if ($last === null) {
        $last = e->amountStaking;
        continue;
      }
      foreach ($last as $key => $val) {
        if (!property_exists($e, $key) || $last->$key != $e->$key) {
          return false;
        }
      }
      $last = e->amountStaking;
    }
    
    return $last;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么