G
G
GRO242020-12-09 09:06:47
PHP
GRO24, 2020-12-09 09:06:47

How to output the most frequent JSON repetitions?

Hi all.
Faced a task that I had never implemented before.

There is a JSON response

{
    "result": [{
        "id": "103513",
        "user": "user_repeat",
        "time_upd": "2020-12-09 08:45:02"
    }, {
        "id": "103517",
        "user": "user_repeat",
        "time_upd": "2020-12-09 08:45:02"
    , {
        "id": "103522",
        "user": "user_no_repeat",
        "time_upd": "2020-12-09 08:45:02
}]
}


I want to find the most repeated nickname in the example is "user": "user_repeat" and display all its IDs.
So that the answer looks something like this
Самый частый юзер: id, id, id
Второй по частоте юзер: id, id, id
Третий по частоте: id, id, id

Who is not difficult, help how to implement
Thank you for your attention

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Immortal_pony, 2020-12-09
@GRO24

$encodedData = '{"result":[{"id":"103513","user":"user_repeat","time_upd":"2020-12-09 08:45:02"},{"id":"103517","user":"user_repeat","time_upd":"2020-12-09 08:45:02"},{"id":"103522","user":"user_no_repeat","time_upd":"2020-12-09 08:45:02"}]}';
$decodedData = json_decode($encodedData, true);
$userRepeats = [];

foreach ($decodedData['result'] as $info) {
    if (!array_key_exists($info['user'], $userRepeats)) {
        $userRepeats[$info['user']] = 0;
    }
    
    $userRepeats[$info['user']]++;
}

arsort($userRepeats);
$mexRepeatsUser = [key($userRepeats)=>current($userRepeats)];

var_dump($userRepeats);
var_dump($mexRepeatsUser);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question