[英]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.