2017-06-22 43 views
1

如何通過知道數組的值來獲得數組中的密鑰?例如,這裏是一個數組:通過值獲取數組中的密鑰

$array = Array("Item1" => array("Number" => "One", "Letter" => "A")); 

只要知道「一」或「A」,我怎麼能得到主鍵名,Item1

我已經看過array_key_valuein_array但我不認爲這些函數對我的類型數組有幫助。

+0

以'foreach' –

回答

1

由於它是一個2d數組,因此您需要在內部數組中搜索該值,因此您必須創建自己的函數來執行此操作。事情是這樣的:

function findInArray($array, $lookup){ 
    //loop over the outer array getting each key and value. 
    foreach($array as $key=>$value){ 
     //if we found our lookup value in the inner array 
     if(in_array($lookup, $value)){ 
      //return the original key 
      return $key; 
     } 
    } 
    //else, return null because not found 
    return null; 
} 

$array = Array("Item1" => array("Number" => "One", "Letter" => "A")); 

var_dump(findInArray($array, 'One')); //outputs string(5) "Item1" 
var_dump(findInArray($array, 'Two')); //outputs null 

演示:https://3v4l.org/oRjHK

0

此功能可以幫助你

function key_of_value($array, $value){ 
    foreach($array as $key=>$val){ 
     if(in_array($value, $val)){ 
      return $key; 
     } 
    } 
    return null; 
} 

echo key_of_value(['Item1'=>['One','Two','Three','Hello',2,6]],'A'); 
0

沒有辦法通過數據迭代左右。這可能是有點更優雅兩個以上foreach循環:

<?php 
$match = null; 
$needle = 'Two'; 
$haystack = [ 
    'Item1' => [ 
     'Number' => 'One', 
     'Letter' => 'A' 
    ], 
    'Item2' => [ 
     'Number' => 'Two', 
     'Letter' => 'B' 
    ], 
    'Item3' => [ 
     'Number' => 'Three', 
     'Letter' => 'C' 
    ], 
]; 

array_walk($haystack, function($entry, $key) use ($needle, &$match) { 
    if(in_array($needle, $entry)) { 
     $match = $key; 
    } 
}); 
var_dump($match); 

輸出顯然是:

string(5) "Item2" 
0

您可以使用array_walk_recursive,反覆數組值遞歸。我寫了一個函數,它返回嵌套數組中的搜索值的主鍵。

<?php 

$array = array("Item1" => array("Number" => "One", "Letter" => "A", 'other' => array('Number' => "Two"))); 

echo find_main_key($array, 'One'); //Output: "Item1" 
echo find_main_key($array, 'A'); //Output: "Item1" 
echo find_main_key($array, 'Two'); //Output: "Item1" 
var_dump(find_main_key($array, 'nothing')); // NULL 

function find_main_key($array, $value) { 
    $finded_key = NULL; 
    foreach($array as $this_main_key => $array_item) { 
     if(!$finded_key) { 
      array_walk_recursive($array_item, function($inner_item, $inner_key) use ($value, $this_main_key, &$finded_key){ 
       if($inner_item === $value) { 
        $finded_key = $this_main_key; 
        return; 
       } 
      }); 
     } 
    } 
    return $finded_key; 
} 
0

這是我會怎麼做:

foreach($array as $key => $value) { if(in_array('One', $value)) echo $key; }

相關問題