user2239695
user2239695

Reputation: 57

Implement array_search() functionality on the rows of a 2d array while requiring multiple associative matches in a row

I want to search a key in a multidimensional array with two values in the condition.

I know how to search a multi-dimensional array with a single search condition:

$key = array_search($journee, array_column($data,'journee'));

but not more than that. Here is my array setup:

Array
(
    [0] => Array
        (
            [pseudo] => titi
            [journee] => 11
            [pts] => 3
        )

    ...
    [10] => Array
        (
            [pseudo] => test
            [journee] => 10
            [pts] => 6
        )

    [11] => Array
        (
            [pseudo] => test
            [journee] => 11
            [pts] => 4
        )

)

If I only put 11 in array_search and for array_column the key journee, it will return 0.

I want to add pseudo in the search condition too (the keys journee and pseudo should be searched for a specific values).

How would I accomplish this?

Upvotes: 4

Views: 7743

Answers (2)

mickmackusa
mickmackusa

Reputation: 47894

To enjoy the efficiency of a conditionally halted loop while excluding the temporary variables from the global scope, use an Immediately Invoked Functional Expression. The qualifying row can be identified using array_diff_assoc() to check that all associative elements in the search array where matched in the given row. Demo

$search = ['pseudo' => 'test', 'journee' => 10];

var_export(
    (function($haystack, $needle) {
        foreach ($haystack as $i => $row) {
            if (!array_diff_assoc($needle, $row)) {
                return $i;
            }
        }
        return null;
    })($array, $search)
);
// output: 10

Upvotes: 0

u_mulder
u_mulder

Reputation: 54841

With one simple function it's not possible.

Here's a solution with two:

$search = ['pseudo' => 'test', 'journee' => 10];
$keys = array_keys(
    array_filter(
        $array,
        function ($v) use ($search) { return $v['pseudo'] == $search['pseudo'] && $v['journee'] == $search['journee']; }
    )
);
$key = $keys[0];

But if you need to find one key only I advise to use foreach & break, because you don't have to iterate over all array of values (what will happen with using array_filter) and stop immediately when certain data is found:

$key = false;
$search = ['pseudo' => 'test', 'journee' => 10];
foreach ($array as $k => $v) {
    if ($v['pseudo'] == $search['pseudo'] && $v['journee'] == $search['journee']) {
        $key = $k;
        // key found - break the loop
        break;
    }
}

Upvotes: 8

Related Questions