dtqysxw4659 2016-12-14 21:19
浏览 53
已采纳

php如何获取数组数组的键值

I have the following setup where I'm trying to use an array of array structure. I'm not sure how to get the key value once the value is found in the array of arrays.

$testboat = 'smallest boat';
$allboats = array(40=>array(1=>'big boat',
                            2=>'bigger boat'
                      ),
                  30=>array(1=>'little boat',
                           2=>'tiny boat',
                           3=>'smallest boat'));

foreach($allboats as $boats){
    foreach($boats as $boat){
       if($testboat == $boat) {

       /*looking to echo the key or value 30; */

      }  

   }
}
  • 写回答

3条回答 默认 最新

  • douyuan4697 2016-12-14 21:32
    关注

    Use the $key => $value syntax of foreach(). Also, no need to loop through the inner arrays:

    foreach($allboats as $key => $boats){
        if(in_array($testboat, $boats)) {
            echo $key;
            break; //if you want to stop after found
        }
    }
    

    If you want to get the outer key and the inner key:

    foreach($allboats as $key => $boats){
        if(($inner_key = array_search($testboat, $boats)) !== false) {
            echo "$key and $inner_key";
            break; //if you want to stop after found
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?