在PHP使用中,array_column 主要是用于获取二维数组中的元素(PHP 5.5新增函数)。
如果我们有时候需要在低版本的PHP环境中使用,怎么办呢?
答:在低于php5.5版本时也就是没有这个函数,那我们就自己动手写一个这样的函数就好了。
重写好的array_column()函数方法源码及案例:<?php
if (!function_exists('array_column')) {
function array_column($array, $column_key, $index_key = null) {
$column_key_isNumber = (is_numeric($column_key)) ? true : false;
$index_key_isNumber = (is_numeric($index_key)) ? true : false;
$index_key_isNull = (is_null($index_key)) ? true : false;
$result = array();
foreach((array)$array as $key=>$val){
if($column_key_isNumber){
$tmp = array_slice($val, $column_key, 1);
$tmp = (is_array($tmp) && !empty($tmp)) ? current($tmp) : null;
} else {
$tmp = isset($val[$column_key]) ? $val[$column_key] : null;
}
if(!$index_key_isNull){
if($index_key_isNumber){
$key = array_slice($val, $index_key, 1);
$key = (is_array($key) && !empty($key)) ? current($key) : null;
$key = is_null($key) ? 0 : $key;
}else{
$key = isset($val[$index_key]) ? $val[$index_key] : 0;
}
}
$result[$key] = $tmp;
}
return $result;
}
}
$res = array(
0 => array(
'id' => 10,
'name' => 'PHP',
),
1 => array(
'id' => 24,
'name' => 'html',
),
2 => array(
'id' => 30,
'name' => 'mysql',
),
3 => array(
'id' => 46,
'name' => 'java',
)
);
$list = array_column($res, 'name', 'id');
print_r($list);
/**************************
输出内容如下:
Array
(
[10] => PHP
[24] => html
[30] => mysql
[46] => java
)
***************************/
$list = array_column($res, 'name');
print_r($list);
/**************************
输出内容如下:
Array
(
[0] => PHP
[1] => html
[2] => mysql
[3] => java
)
***************************/
?>
浏览器启用弹出窗口过滤功能,将无法跳转到下载页。在浏览器地址栏右边符号提示处点击允许就可以了!
郑重声明:
1、本站源码仅供个人学习研究和交流使用,请于下载后二十四小时内删除
2、本站大多资源来源于互联网、用户分享,仅供学习交流使用,本站不提供任何技术支持
3、本站联系方式Email:admin@youhutong.com ,收到邮件会第一时间处理。
4、如侵犯到任何版权问题,请立即告知本站(立即在线告知),本站将及时删除并致以最深的歉意