Skip to content
Advertisement

Remove similar from foreach

Trying use array_unique but this did not help, since not all fields are repeated for me. My array:

'Rows' => 
  array (
    0 => 
        array (
        'HotelId' => 94852,
        'OfferId' => 858080496,
        'OfferIdStr' => '858080496',
        'Price' => 2762,
    ),
    1 => 
      array (
        'HotelId' => 94852,
        'OfferId' => 858080497,
        'OfferIdStr' => '858080497',
        'Price' => 3000,
    ),

And my try:

$allHotels['Rows'] = array_unique($allHotels['Rows'], SORT_REGULAR);

Changed flags, didn’t help either (SORT_NORMAL, etc…). It deletes absolutely everything, i need to ignore the HotelId replay, only first need.

Advertisement

Answer

If you want to delete duplicated entries based solely on the HotelId value, it’s probably easiest just to iterate over the array, storing the seen HotelId values and deleting the current entry if it’s HotelId value has already been seen.

$seenHotels = array();
foreach ($allHotels['Rows'] as $key => $hotel) {
    if (in_array($hotel['HotelId'], $seenHotels)) {
        unset($allHotels['Rows'][$key]);
    }
    else {
        $seenHotels[] = $hotel['HotelId'];
    }
}
print_r($allHotels);

Demo on 3v4l.org

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement