J
J
JTester2021-08-11 21:29:17
PHP
JTester, 2021-08-11 21:29:17

How to find a user and how to find out where there are fewer users?

Hello! There is such an array

$arr = [
            'test1' => ['users' => ['test']],
            'test2' => ['users' => []],
            'test3' => ['users' => []],
            'test4' => ['users' => []]
        ];

How can I find test in this array and get the key of this array itself, that is, if I have 'test' in the 'test1' array, then I need to display this test1.

Another question is how to find where the least users are in these arrays and get the key again to add it to the users array

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Sokolov, 2021-08-11
@JTester

$search = 'test';

$contains = array_keys(array_filter($arr, function($item) use ($search) { return in_array($search, $item['users']); }));

print_r($contains);  // ['test1']

The key of one containing the shortest subarray 'users':
$keys = array_keys($arr);
usort($keys, function($a, $b) use ($arr) {
    return count($arr[$a]['users']) - count($arr[$b]['users']);
});

$shortest = $keys[0];

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question