php获取关联数组key的index,如何根据key从关联数组中获取索引?
微wx笑
2023-05-29【编程语言】
42
0
0关键字:
php 关联数组 索引
很多文章讲的其实是获取的key,并不是索引,这里讲的索引是像一维数据的0、1、2、等这样的数据。
很多文章讲的其实是获取的key,并不是索引,这里讲的索引是像一维数组的0、1、2、等这样的数据。
给定数组:
1 2 3 4 5 6 7 8 9 10 | $messageType = [ 'text' => '文本' , 'image' => '图片' , 'voice' => '语音' , 'video' => '视频' , 'link' => '链接' , 'location' => '位置' , 'subscribe' => '订阅' , 'unsubscribe' => '取消订阅' ]; |
想通过 text 得到的是 0,传递 voice 等到的是 2
实现方法
要正确获取关联数组的数字索引,我们应该:
1. 定义一个函数,传入要搜索的key和关联数组
2. 在函数内部,先使用array_keys()获取数组的所有key
3. 然后遍历这个key数组,如果找到搜索的key,则返回其对应的数字索引
4. 如果未找到,返回-1
所以,我们可以定义这样一个函数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | /** 获取 $key 在关联数组 $messageType 中的索引位置 */ function array_index( $key , $messageType ){ if ( array_key_exists ( $key , $messageType )) { $keys = array_keys ( $messageType ); for ( $i = 0; $i < count ( $keys ); $i ++){ if ( $key === $keys [ $i ]){ return $i ; } } } return -1; } |
使用方法
1 2 | echo 'index ==' . array_index( 'voice' , $messageType ) . "<br>" ; //输出 index ==2 echo 'index ==' . array_index( 'text' , $messageType ) . "<br>" ; //输出 index ==0 |
本文由 微wx笑 创作,采用 署名-非商业性使用-相同方式共享 4.0 许可协议,转载请附上原文出处链接及本声明。
原文链接:https://www.ivu4e.cn/blog/lang/2023-05-29/1899.html