简体   繁体   English

如何计算PHP数组中的唯一值

[英]How to count unique value in array in php

I am getting data from database in following format,I just want to get data,How many restaurant name (count) in which country,How can i do this ? 我正在从数据库中获取以下格式的数据,我只想获取数据,在哪个国家/地区有多少家餐厅名称(数量),我该怎么做? How can i change following array/object 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
                 )
        )       
    ....
 )

As object can have same keys I will assume you have array of object for each restaurant object. 由于对象可以具有相同的键,因此我假设您为每个餐厅对象都有一个对象数组。

First I recommend get only the countries to separate array as: 首先,我建议仅获取将数组分开的国家/地区:

foreach($objectArray as $restaurant)
    $countries[] = $restaurant->location->country;

Now you can use array-count-values to get number of object according the countries: 现在,您可以使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM