自己写的兼容低于PHP 5.5版本的array_column()函数
发布人:shili8
发布时间:2022-12-11 16:33
阅读次数:20
array_column 用于获取二维数组中的元素(php 5.5新增函数),但我们有时候需要在低版本的php环境中使用…
if( ! function_exists('array_column')) { function array_column($input, $columnkey, $indexkey = null) { $columnkeyisnumber = (is_numeric($columnkey)) ? true : false; $indexkeyisnull = (is_null($indexkey)) ? true : false; $indexkeyisnumber = (is_numeric($indexkey)) ? true : false; $result = array(); foreach ((array)$input as $key => $row) { if ($columnkeyisnumber) { $tmp = array_slice($row, $columnkey, 1); $tmp = (is_array($tmp) && !empty($tmp)) ? current($tmp) : null; } else { $tmp = isset($row[$columnkey]) ? $row[$columnkey] : null; } if ( ! $indexkeyisnull) { if ($indexkeyisnumber) { $key = array_slice($row, $indexkey, 1); $key = (is_array($key) && ! empty($key)) ? current($key) : null; $key = is_null($key) ? 0 : $key; } else { $key = isset($row[$indexkey]) ? $row[$indexkey] : 0; } } $result[$key] = $tmp; } return $result; } }