【问题标题】:How to compare object by properties如何按属性比较对象
【发布时间】:2016-09-09 06:59:37
【问题描述】:

我正在尝试按属性比较对象。我想通过他们的 hotelId 属性来比较它们。每家酒店的hotelId 都是唯一的。例如,如果我有这样的对象数组:

   array(4) [
       0 => stdClass(5) {
          hotelId => 238
          hotelName => "Bellevue Dominican Bay" (22)      
       }
       1 => stdClass(5) {
          hotelId => 5432
          hotelName => "Puerto Plata Village" (20)
       }
       2 => stdClass(5) {
          hotelId => 238
          hotelName => "Puerto" (20)
       }
    ]

我想要做的是使用他们的hotelId 拥有独特的对象。

到目前为止我的代码:

$uniqueHotelObjects = array();
foreach($arrayOfHotelObjects as $hotel){
    foreach ($uniqueHotelObjects as $uniqueHotel) {
        if($hotel->hotelId !==  $uniqueHotel->hotelId){
            //??   
        }
    }
}

【问题讨论】:

  • 当你发现重复时你想做什么?
  • 当我有副本时,我只想保留一个对象(第一个)

标签: php arrays object


【解决方案1】:

如果使用ID作为数组键,只需要一个循环:

$uniqueHotelObjects = array();
foreach($arrayOfHotelObjects as $hotel){
    // check if the element already exists in the unique array
    if (!array_key_exists($hotel->hotelId, $uniqueHotelObjects) {
        $uniqueHotelObjects[$hotel->hotelId] = $hotel;
    }
}

如果您想保留最后一个条目,只需删除 if 语句即可。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-10
    • 2013-08-26
    • 1970-01-01
    • 1970-01-01
    • 2012-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多