0

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 ?

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
                 )
        )       
    ....
 )
3
  • 1
    an array cannot have same indexes multiple time. please correct input data Commented Jun 3, 2019 at 8:10
  • @ Alive to die,ya,this is just example,hope you understand my question,please help me Commented Jun 3, 2019 at 8:13
  • You want count of restaurants country wise or names of restaurants also? I see this is mongodb stuff, do you want query for that or in php? Commented Jun 3, 2019 at 8:52

2 Answers 2

1

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:

print_r(array_count_values($countries));
Sign up to request clarification or add additional context in comments.

Comments

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.