gpt4 book ai didi

php - 基于特定键值的唯一数组

转载 作者:行者123 更新时间:2023-12-05 08:43:38 26 4
gpt4 key购买 nike

我有以下数组:

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
)

)

我有两个不同的酒店 ID key 。我只想提取一个元素(第一个元素),其中 hotelID 在整个数组中是唯一的。我正在尝试使用以下代码:

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

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

谁能给我一个提示?

最佳答案

如果寻找第一个元素:

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

)

关于php - 基于特定键值的唯一数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25959808/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com