phparraysmultidimensional-arrayfilteringassociative

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?


Solution

  • 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;
        }
    }