2014-09-21 41 views
0

值我有以下的數組:在基座獨特陣列上的特定鍵

Array 
(
    [0] => Array 
    (
     [hotelID] => 10 
     [hotelcategoryID] => 12 
     [hotelName] => Grand Forest Metsovo 
     [hotelShortDescription] => 
     [hotelVisible] => 1 
     [roomID] => 2 
    ) 

    [1] => Array 
    (
     [hotelID] => 10 
     [hotelcategoryID] => 12 
     [hotelName] => Grand Forest Metsovo 
     [hotelShortDescription] => 
     [hotelVisible] => 1 
     [roomID] => 3 
    ) 

    [2] => Array 
    (
     [hotelID] => 10 
     [hotelcategoryID] => 12 
     [hotelName] => Grand Forest Metsovo 
     [hotelShortDescription] => 
     [hotelVisible] => 1 
     [roomID] => 4 
    ) 

    [3] => Array 
    (
     [hotelID] => 14 
     [hotelcategoryID] => 7 
     [hotelName] => Hotel Metropolis 
     [hotelShortDescription] => 
     [hotelVisible] => 1 
     [roomID] => 23 
    ) 

    [4] => Array 
    (
     [hotelID] => 14 
     [hotelcategoryID] => 7 
     [hotelName] => Hotel Metropolis 
     [hotelShortDescription] => 
     [hotelVisible] => 1 
     [roomID] => 24 
    ) 

) 

我有兩個不同hotelID密鑰。我想只提取一個元素(第一個元素),其中hotelID在整個數組中是唯一的。我想用下面的代碼:

$data['uniqueHotels'] = array_map('unserialize', array_unique(array_map('serialize', $hotels))); 

但是沒有任何運氣到目前爲止。

任何人都可以給我一個提示嗎?

+0

你的問題不清楚。你在找什麼?一個具有獨特酒店ID的數組?如何處理重複?當hotelID相同時,其他字段是否一樣? (不!) – 2014-09-21 13:46:32

+0

是的,我只想要不同的酒店ID鍵。第一個元素會做。其他元素可能會被釋放。 – user2417624 2014-09-21 13:52:27

回答

1

您可以簡單地遍歷數組並將它們添加到一個新數組中,索引爲hotelID。這樣,任何重複只會覆蓋現有的價值,你最終每家酒店一個條目:

$unique = array(); 

foreach ($hotels as $value) 
{ 
    $unique[$value['hotelID']] = $value; 
} 

$data['uniqueHotels'] = array_values($unique); 
+0

謝謝,那是... – user2417624 2014-09-21 14:04:04

1

如果找的第一個元素:

<?php 

$hotels = array(
    array(
    'id' => 1, 
    'hotelID' => 10 
), 
    array(
    'id' => 2, 
    'hotelID' => 10, 
), 
    array(
    'id' => 3, 
    'hotelID' => 20, 
), 
    array(
    'id' => 4, 
    'hotelID' => 20, 
), 
); 


function getUniqueHotels($hotels) { 
    $uniqueHotels = array(); 

    foreach($hotels as $hotel) { 
    $niddle = $hotel['hotelID']; 
    if(array_key_exists($niddle, $uniqueHotels)) continue; 
    $uniqueHotels[$niddle] = $hotel; 
    } 

    return $uniqueHotels; 
} 

$unique_hotels = getUniqueHotels($hotels); 
print_r($unique_hotels); 

結果:

Array 
(
    [10] => Array 
     (
      [id] => 1 
      [hotelID] => 10 
     ) 

    [20] => Array 
     (
      [id] => 3 
      [hotelID] => 20 
     ) 

) 
1

沿着你所嘗試的方向,

array_unique(array_map(function($hotel) { return $hotel['hotelID']; }, $array))