2013-01-15 169 views
0

我嘗試獲取匹配值的數組鍵值。 它看起來像這樣:查找匹配值的數組鍵值

$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"; 

如何獲取數組鍵如「1」($ array [1]),通過將var「$ someId = 2」與數組中的唯一ID($ array [1] [id])進行匹配?

基本上:$ someId === $ array [x] [id]>返回數組$ array [x]它匹配的地方。

+0

[whathaveyoutried點... COM](http://whathaveyoutried.com) –

回答

2

一個簡單的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 
    } 
} 

如果你想那麼關鍵改爲

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

array_filter()保留關聯

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

var_dump(array_keys($result));