自己写的兼容低于PHP 5.5版本的array_column()函数

yipeiwu_com6年前PHP代码库

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;
  }
}

相关文章

php读取javascript设置的cookies的代码

下面给代码: 复制代码 代码如下: <script language="JavaScript" type="text/javascript"> function setmyc...

PHP图片处理类 phpThumb参数用法介绍

phpThumb几个基本参数 一些有用的参数列一下: src:目标图片的地址 w:输出图片的宽度 h:输出图片的高度(如果不指定他将按w参数等比缩放) q:输出如果是JPG格式的,可以规...

Cakephp 执行主要流程

加载基本文件 cake/basics.php 里面定义了常用的方法以及时间常量 $TIME_START = getMicrotime(); 记录开始执行时间 cake/config/pa...

PHP中遍历stdclass object的实现代码

需要操作的数据: 复制代码 代码如下: $test =Array ( [0] => stdClass Object ( [tags] => 最快的车,Bloodhound,S...

php变量范围介绍

例如: 复制代码 代码如下: <?php $a = 1; include 'b.inc'; ?> 这里变量 $a 将会在包含文件 b.inc 中生效。但是,在用户自定义函数...