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条)

报告相同问题?

悬赏问题

  • ¥20 蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏