array_column()函数 php低版本兼容处理

在使用php内置的函数进行数组排序时,发现使用该函数array_column()时报错了,上网一查发现是php版本不支持(当时是php5.4,这个函数是php5.5才支持),所以在使用是就可以自己重新定义一下该函数,就可以通用了,下面代码是按照数组内view_num字段降序排序,代码如下:

a();
function a()
{
    $info = array(
        0 =>
            array(
                'id' => '12',
                'name' => 'aaaa',
                'view_num' => 20,
            ),
        1 =>
            array(
                'id' => '22',
                'name' => 'dddd',
                'view_num' => 11,
            ),
        2 =>
            array(
                'id' => '13',
                'name' => 'bbbb',
                'view_num' => 19,
            ),
        3 =>
            array(
                'id' => '25',
                'name' => 'ccccc',
                'view_num' => 39,
            ),
    );
    $flag = _array_column($info, 'view_num', 'id');
    array_multisort($flag, SORT_DESC, $info);
    var_dump($info);
}
/**
 * 返回数组中指定的一列
 * @param $input            需要取出数组列的多维数组(或结果集)
 * @param $columnKey        需要返回值的列,它可以是索引数组的列索引,或者是关联数组的列的键。 也可以是NULL,此时将返回整个数组(配合index_key参数来重置数组键的时候,非常管用)
 * @param null $indexKey    作为返回数组的索引/键的列,它可以是该列的整数索引,或者字符串键值。
 * @return array            返回值
 */
function _array_column($input, $columnKey, $indexKey = null)
{
    if (!function_exists('array_column')) {
        $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;
    } else {
        return array_column($input, $columnKey, $indexKey);
    }
}

输出结果为:

array(4) {
  [0]=>
  array(3) {
    ["id"]=>
    string(2) "25"
    ["name"]=>
    string(5) "ccccc"
    ["view_num"]=>
    int(39)
  }
  [1]=>
  array(3) {
    ["id"]=>
    string(2) "12"
    ["name"]=>
    string(4) "aaaa"
    ["view_num"]=>
    int(20)
  }
  [2]=>
  array(3) {
    ["id"]=>
    string(2) "13"
    ["name"]=>
    string(4) "bbbb"
    ["view_num"]=>
    int(19)
  }
  [3]=>
  array(3) {
    ["id"]=>
    string(2) "22"
    ["name"]=>
    string(4) "dddd"
    ["view_num"]=>
    int(11)
  }
}

猜你喜欢

转载自blog.csdn.net/fmyzc/article/details/81450754
今日推荐