基于特定键值的唯一数组

时间:2014-09-21 13:40:31

标签: php arrays

我有以下数组:

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)));

但到目前为止没有任何运气。

任何人都可以给我一个提示吗?

4 个答案:

答案 0 :(得分:2)

您可以简单地遍历数组并将它们添加到由hotelID索引的新数组中。这样,任何重复项都会覆盖现有值,最终每个酒店只有一个条目:

$unique = array();

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

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

答案 1 :(得分:2)

如果要找第一个元素:

<?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
        )

)

答案 2 :(得分:1)

沿着你正在尝试的方向,

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

答案 3 :(得分:1)

这是一个动态的解决方案:

function uniqueAssocArray($array, $uniqueKey){
 $unique = array();

 foreach ($array as $value){
  $unique[$value[$uniqueKey]] = $value;
 }

 $data = array_values($unique);

 return $data;
}

使用方法: uniqueAssocArray($yourArray, 'theKey');