0

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 2x
  • USA appeared 2x
  • m appeard 2x
  • admin appeared 2x

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.

Reza Saadati
  • 1,224
  • 13
  • 27

1 Answers1

1

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

davidev
  • 7,694
  • 5
  • 21
  • 56
  • 1
    Thanks for your answer. So that means I have to create arrays for all columns first? – Reza Saadati Oct 08 '19 at 22:52
  • Yeah correct. That would be my way to approach it. An array for city, country, gender.. .and in the end get the most used value for each and create a new JSON from it. Would be a good way to create a function for that. – davidev Oct 08 '19 at 22:53
  • Okay that sounds to be a good way. Great, thank you for your help! – Reza Saadati Oct 08 '19 at 22:56
  • 1
    @RezaSaadati No problem, I will think about it if I see another way to approach this prob – davidev Oct 08 '19 at 22:58