Reputation: 1274
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
Chicago
appeared 2xUSA
appeared 2xm
appeard 2xadmin
appeared 2xHow 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
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