[英]How to count unique value in array in php
我正在從數據庫中獲取以下格式的數據,我只想獲取數據,在哪個國家/地區有多少家餐廳名稱(數量),我該怎么做? 我如何更改以下數組/對象在php中?
stdClass Object
(
[_id] => 5ce405ced246f713b6256f3a
[location] => stdClass Object
(
[country] => Kuwait
)
[employerDetails] => Array
(
[0] => stdClass Object
(
[restraunt_name] => test1
)
)
[_id] => 5ce405ced246f713b6277373
[location] => stdClass Object
(
[country] => Kuwait
)
[employerDetails] => Array
(
[0] => stdClass Object
(
[restraunt_name] => test2
)
)
....
)
由於對象可以具有相同的鍵,因此我假設您為每個餐廳對象都有一個對象數組。
首先,我建議僅獲取將數組分開的國家/地區:
foreach($objectArray as $restaurant)
$countries[] = $restaurant->location->country;
現在,您可以使用array-count-values根據國家/地區獲取對象數:
print_r(array_count_values($countries));
$countries = array();
//first get all countries list
foreach ($array as $data) {
if (!in_array($data->location->country, $countries)) {
array_push($countries, $data->location->country);
}
}
//get restraunt county wise
foreach ($array as $key => $data) {
//if (in_array($data->location->country, $countries)) {
if (!empty($data->location->country) && !empty($data->employerDetails[0]->restraunt_name)) {
$countries_f[$data->location->country][$key] = $data->employerDetails[0]->restraunt_name;
}
//}
}
//get count of restraunt in each ocuntry
foreach ($countries as $cnt) {
echo 'count of' . $cnt = count($countries_f[$cnt]) . '<br />';
}
echo "<pre>";
print_r($countries_f);
die;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.