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

时间:2019-06-03 08:05:22

标签: php arrays object

我正在从数据库中以以下格式获取数据,我只想获取数据,有多少家餐厅(计数) 在哪个国家,我该怎么办?如何更改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
                 )
        )       
    ....
 )

2 个答案:

答案 0 :(得分:1)

由于对象可以具有相同的键,所以我假设您为每个餐厅对象都有一个对象数组。

首先,我建议仅将国家/地区分隔为:

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

现在您可以使用array-count-values根据国家/地区获取对象数:

print_r(array_count_values($countries));

答案 1 :(得分:0)

$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;
相关问题