找到匹配值的数组键

时间:2022-12-29 20:13:09

I try to get the array key of matching values. It looks like that:

我尝试获取匹配值的数组键。它看起来像这样:

$someId = 2

$array[0][id]   = "1";
$array[0][firstname]  = "dude1";

$array[1][id]   = "2";
$array[1][firstname]  = "dude2";

$array[2][id]   = "3";
$array[2][firstname]  = "dude3";

How I get the array key e.g. "1" ($array[1]), by matching the var "$someId = 2" with the unique IDs ( $array[1][id]) in the array?

我如何获得数组键,例如“1”($ array [1]),通过将var“$ someId = 2”与数组中的唯一ID($ array [1] [id])进行匹配?

Basically: $someId === $array[x][id] > returns the array $array[x] where it matches.

基本上:$ someId === $ array [x] [id]>返回匹配的数组$ array [x]。

2 个解决方案

#1


2  

A simple foreach will do it:

一个简单的foreach将会这样做:

$someId = 2;

foreach($array as $person)
{
    if($person['id'] == $someId)
    {
        // found a match, do something with $person
        // ...
        break; // remove the break if you want to continue searching after a match
    }
}

If you want the key then change to

如果你想要密钥,那么改为

foreach($array as $key => $person)

#2


0  

array_filter() retains associativity

array_filter()保留关联性

$result = array_filter(
    $array,
    function ($item) use ($personId) {
        return ($item['id'] == $personId);
    }
);

var_dump(array_keys($result));

#1


2  

A simple foreach will do it:

一个简单的foreach将会这样做:

$someId = 2;

foreach($array as $person)
{
    if($person['id'] == $someId)
    {
        // found a match, do something with $person
        // ...
        break; // remove the break if you want to continue searching after a match
    }
}

If you want the key then change to

如果你想要密钥,那么改为

foreach($array as $key => $person)

#2


0  

array_filter() retains associativity

array_filter()保留关联性

$result = array_filter(
    $array,
    function ($item) use ($personId) {
        return ($item['id'] == $personId);
    }
);

var_dump(array_keys($result));