user2239695 user2239695 - 1 month ago 6
PHP Question

array_search multidimensional array with multiple value

I search on Google a lot but i didn't find an answer (or I didn't understand it).

Here is my problem :
I want to search the key in a multidimensional array with two value in the condition.

I know how to search in a mutlidim array with one condition :

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


Here is my array :

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 juste put
11
in array_search for the colunm
journee
, it will return 0.

I want to add
pseudo
in the search condition.

Is it possible with a simple function ?

Or must I use array_keys() ? (Does it work with multidim array ?)

Thanks in advance for any help,

Best Regards.

Answer

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