Reza Saadati
Reza Saadati

Reputation: 1274

Get the most listed values from all JSONs

I have multiple JSON strings, which are stored in my database.

Here are 3 example of how they could look like:

Example 1

{
    "request": {
        "city": "Chicago",
        "country": "USA",
        "gender": "m"
    }
}

Example 2

{
    "request": {
        "city": "Chicago",
        "country": "USA",
        "gender": "f",
        "role": "admin"
    }
}

Example 3

{
    "request": {
        "city": "Paris",
        "country": "France",
        "gender": "m",
        "language": "French",
        "role": "admin"
    }
}

I would like to compare all JSONs with each other and create a new JSON with the most listed values. This is how the result should be:

Result

{
    "request": {
        "city": "Chicago",
        "country": "USA",
        "gender": "m",
        "role": "admin"
    }
}

Why?

Because we had 3 JSONS and

How can I get that JSON that I need?

PS: I don't need a finished code. It's enough if someone could explain me HOW I could do it.

Upvotes: 0

Views: 48

Answers (1)

davidev
davidev

Reputation: 8517

I would create a array for every JSON key (role, gender, city ...)

Then when I parse the JSON, I would add the values to the specific array.

In the end just count the most used values in the array and output the value.

$city = ["Chicago", "Los Angeles", "Florida", "Los Angeles", "Chicago", "Chicago", "Los Angeles", "Los Angeles"];

$count = array_count_values($city);

arsort($count); 

$mostUsedCity = key($count); 

echo $mostUsedCity;

Output: Los Angeles

Upvotes: 1

Related Questions