如何按属性比较对象

时间:2016-09-09 06:59:38

标签: php arrays object

我正在尝试按对象属性进行比较。我想用他们的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){
            //??   
        }
    }
}

1 个答案:

答案 0 :(得分:2)

如果您使用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语句。