dtqysxw4659 2016-12-14 13: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 13: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部