Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search an multi-dimensional array with multiple search conditions?

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?

like image 439
user2239695 Avatar asked Feb 05 '23 18:02

user2239695


1 Answers

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;
    }
}
like image 145
u_mulder Avatar answered May 20 '23 08:05

u_mulder