从数组中获取值而不进行迭代


Get values from array without iteration

我有这个数组

Array
(
    [0] => Array
        (
            [column_name] => product_id
        )
    [1] => Array
        (
            [column_name] => product_name
        )
    [2] => Array
        (
            [column_name] => product_slug
        )
)

我需要一个只包含列名称的数组:

array('product_id', 'product_name', 'product_slug')

我制作了一个空数组,并像这样迭代主数组:

$data = array();
foreach ($result as $key => $res) {
    $data[] = $res['column_name'];
}

除了迭代,还有其他方法吗?

如果您正在运行PHP > 5.5,请尝试使用array_column函数。像这样:

$data = array_column($result, 'column_name');
print_r($data);

如果您的PHP < 5.5,请使用以下内容:

//Signature: array array_column ( array $input , mixed $column_key [, mixed $index_key ] )
if( !function_exists( 'array_column' ) ) {
    function array_column( array $input, $column_key, $index_key = null ) {
        $result = array();
        foreach( $input as $k => $v )
            $result[ $index_key ? $v[ $index_key ] : $k ] = $v[ $column_key ];
        return $result;
    }
}

您可以在使用PHP>5.5时使用array_column()。

$data = array();
$data = array_column($result, 'column_name');
print_r($first_names);

如果您的版本低于此版本,请添加以下代码:

<?php
if (! function_exists('array_column')) {
    function array_column(array $input, $columnKey, $indexKey = null) {
        $array = array();
        foreach ($input as $value) {
            if ( ! isset($value[$columnKey])) {
                trigger_error("Key '"$columnKey'" does not exist in array");
                return false;
            }
            if (is_null($indexKey)) {
                $array[] = $value[$columnKey];
            }
            else {
                if ( ! isset($value[$indexKey])) {
                    trigger_error("Key '"$indexKey'" does not exist in array");
                    return false;
                }
                if ( ! is_scalar($value[$indexKey])) {
                    trigger_error("Key '"$indexKey'" does not contain scalar value");
                    return false;
                }
                $array[$value[$indexKey]] = $value[$columnKey];
            }
        }
        return $array;
    }
}