-1

I have two arrays $users and $find. I need count how many matches in $users if $find array would be changed.

$users = array(
    [
        'name' => 'Jim',
        'sname' => 'Carrey'
    ],
    [
        'name' => 'Michael',
        'sname' => 'Douglas'
    ],
    [
        'name' => 'Michael',
        'sname' => 'Jackson'
    ],
    [
        'name' => 'Michael',
        'sname' => 'Jordan'
    ]
);

Find array changed dynamically. It may be:

$find = array (
    'name' => array('Michael'),
    'sname' => array('Douglas', 'Jordan')
);

OR:

$find = array (
    'sname' => array('Carrey', 'Jordan')
);

I'm looking for a one-size-fits-all solution for for any values in $find array. Thanks!

I can count if I have static keys and values in $find array:

$result = array_filter($users, function($user) {
    return in_array($user['name'], ['Michael', 'Jim']) && in_array($user['sname'], ['Douglas', 'Jordan', 'Carrey']);
});
$count = count($result);
print_r($result);

But I don't understand how count if it should be dynamic keys and values in $find array.

1

1 Answer 1

0

If you want to deal with an unknown number of items in $find, then you will need to loop over them. The use keyword helps to "inject" $find into your callback function. In your loop, you can return false, if the in_array check for the current find item results in false, otherwise you return true after the loop.

$result = array_filter($users, function($user) use ($find) {
    foreach($find as $col => $values) {
        if(!in_array($user[$col], $values)) {
            return false;
        }
    }
    return true;
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.