今天是:2025年2月27日 星期四
记住用户名密码
如果想编写兼容低于PHP 5.5版本的array_column()函数,可以按照以下步骤:
定义一个新函数,例如my_array_column():
1 2 3 | function my_array_column( array $input , $column_key , $index_key =null) { // ... } |
这里定义了一个函数my_array_column,接收三个参数:一个数组$input,列键$column_key和索引键$index_key。其中,$input为必填参数,因为它是要进行操作的数据源。
根据PHP 5.5版本的array_column()函数的文档,可以看出它的核心功能是提取二维数组中指定列的值并返回。在自己编写的函数中,需要先检查PHP版本是否低于5.5,如果是,则按照旧版本的方式提取指定列的值:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | if (!function_exists( 'array_column' )) { function my_array_column( $input , $column_key , $index_key =null) { $output = array (); foreach ( $input as $row ) { if ( $index_key !== null && array_key_exists ( $index_key , $row )) { if ( array_key_exists ( $column_key , $row )) { $output [ $row [ $index_key ]] = $row [ $column_key ]; } } else { $output [] = $row [ $column_key ]; } } return $output ; } } else { function my_array_column( array $input , $column_key , $index_key =null) { return array_column( $input , $column_key , $index_key ); } } |
这里使用了function_exists()函数来检查array_column()函数是否存在,如果不存在,则执行my_array_column()函数。代码中首先定义了一个空数组$output,然后遍历$input数组中的每一行,使用if语句检测$index_key是否为null,若不是,则将$output数组的键名设为这一行的索引键值,将键值设为这一行的列键值;否则直接将列键值存入$output数组。最后将$output数组返回。
再加上一些错误处理的代码,例如,当$column_key无效时,返回false:
1 2 3 4 5 6 7 8 9 10 11 12 13 | if (! is_array ( $input )) { trigger_error( 'my_array_column() expects parameter 1 to be array, ' . gettype ( $input ) . ' given' , E_USER_WARNING); return null; } if ( $index_key !== null && ! is_string ( $index_key ) && ! is_int ( $index_key )) { trigger_error( 'my_array_column(): The index key should be either a string or an integer' , E_USER_WARNING); return null; } if (! is_string ( $column_key ) && ! is_int ( $column_key )) { trigger_error( 'my_array_column(): The column key should be either a string or an integer' , E_USER_WARNING); return false; } |
这里使用了trigger_error()函数来跑出错误信息,如参数类型不正确等情况。
下面是两个示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 | $cars = array ( array ( 'id' => 1, 'make' => 'Toyota' , 'model' => 'Corolla' , 'year' => 2017), array ( 'id' => 2, 'make' => 'Honda' , 'model' => 'Civic' , 'year' => 2016), array ( 'id' => 3, 'make' => 'Ford' , 'model' => 'Fusion' , 'year' => 2015) ); // 输出指定列键名的所有行的值 $result1 = my_array_column( $cars , 'make' ); print_r( $result1 ); // 输出指定列键名的所有行的索引键值 $result2 = my_array_column( $cars , 'make' , 'id' ); print_r( $result2 ); |
输出结果:
1 2 3 4 5 6 7 8 9 10 11 12 | Array ( [0] => Toyota [1] => Honda [2] => Ford ) Array ( [1] => Toyota [2] => Honda [3] => Ford ) |
第一个示例中,输出了$cars数组的所有make列的值。第二个示例中输出了$cars数组所有行的make列值,并且以id列的值作为新数组的键名。
目前有 0 条留言 其中:访客:0 条, 博主:0 条