How to search by value and get key in multidimensional arrays?

怎甘沉沦 提交于 2019-12-13 10:25:33

问题


I have a multidimensional array like this:

$a['bla1']['blub1']="test123";
$a['bla1']['blub2']="test1234";
$a['bla1']['blub3']="test12345";
$a['bla2']['blub1']="test123456";
$a['bla2']['blub2']="test12344e45";
$a['bla2']['blub3']="test12345335";

How to search by value and get back bla1 or bla2? I don't need the subkey, only the key.


回答1:


try this:

function searcharray($a, $value)
{
   foreach($a as $key1 => $keyid)
   {

  foreach($keyid as $key => $keyid2)
   {
      if ( $keyid2 === $value )
         return $key.','.$key1;
   }
}
   return false;
}



回答2:


This function recursively searches an array to any depth and returns the main key under which $needle is found:

function get_main_key($arr, $needle) {
    $out = FALSE;
    foreach ($arr as $key => $value) {
        if ($value == $needle) {
            $out = $key;
        } elseif (is_array($value)) {
            $ret = get_main_key($value, $needle);
            $out = ( ! empty($ret)) ? $key : $out;
        }
    }
    return $out;
}


来源:https://stackoverflow.com/questions/17806116/how-to-search-by-value-and-get-key-in-multidimensional-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!