Array column in php multidimensional

[PHP 5 >= 5.5.0, PHP 7, PHP 8]

array_columnReturn the values from a single column in the input array

Description

array_column[array $array, int|string|null $column_key, int|string|null $index_key = null]: array

Parameters

array

A multi-dimensional array or an array of objects from which to pull a column of values from. If an array of objects is provided, then public properties can be directly pulled. In order for protected or private properties to be pulled, the class must implement both the __get[] and __isset[] magic methods.

column_key

The column of values to return. This value may be an integer key of the column you wish to retrieve, or it may be a string key name for an associative array or property name. It may also be null to return complete arrays or objects [this is useful together with index_key to reindex the array].

index_key

The column to use as the index/keys for the returned array. This value may be the integer key of the column, or it may be the string key name. The value is cast as usual for array keys [however, prior to PHP 8.0.0, objects supporting conversion to string were also allowed].

Return Values

Returns an array of values representing a single column from the input array.

Changelog

VersionDescription
8.0.0 Objects in columns indicated by index_key parameter will no longer be cast to string and will now throw a TypeError instead.

Examples

Example #1 Get the column of first names from a recordset

The above example will output:

Array
[
    [0] => John
    [1] => Sally
    [2] => Jane
    [3] => Peter
]

Example #2 Get the column of last names from a recordset, indexed by the "id" column

The above example will output:

Array
[
    [2135] => Doe
    [3245] => Smith
    [5342] => Jones
    [5623] => Doe
]

Example #3 Get the column of usernames from the public "username" property of an object

The above example will output:

Array
[
    [0] => user 1
    [1] => user 2
    [2] => user 3
]

Example #4 Get the column of names from the private "name" property of an object using the magic __get[] method.

The above example will output:

Array
[
    [0] => Fred
    [1] => Jane
    [2] => John
]

If __isset[] is not provided, then an empty array will be returned.

mohanrajnr at gmail dot com

7 years ago

if array_column does not exist the below solution will work.

if[!function_exists["array_column"]]
{

    function array_column[$array,$column_name]
    {

        return array_map[function[$element] use[$column_name]{return $element[$column_name];}, $array];

    }

}

WARrior

8 years ago

You can also use array_map fucntion if you haven't array_column[].

example:

$a = array[
    array[
        'id' => 2135,
        'first_name' => 'John',
        'last_name' => 'Doe',
    ],
    array[
        'id' => 3245,
        'first_name' => 'Sally',
        'last_name' => 'Smith',
    ]
];

array_column[$a, 'last_name'];

becomes

array_map[function[$element]{return $element['last_name'];}, $a];

balbuf

4 years ago

This function does not preserve the original keys of the array [when not providing an index_key].

You can work around that like so:

yangmeishu at live dot com

2 years ago

Please note that if you use array_column to reset the index, when the index value is null, there will be different results in different PHP versions, examples

till at etill dot net

7 years ago

Some remarks not included in the official documentation.

1] array_column does not support 1D arrays, in which case an empty array is returned.

2] The $column_key is zero-based.

3] If $column_key extends the valid index range an empty array is returned.

nino at recgr dot com

5 years ago

array_column implementation that works on multidimensional arrays [not just 2-dimensional]:

antonfedonjuk at gmail dot com

7 years ago

My version is closer to the original than //github.com/ramsey/array_column

Carlos Granados

5 years ago

Here's a neat little snippet for filtering a set of records based on a the value of a column:

Anonymous

6 years ago

I added a little more functionality to the more popular answers here to support the $index_key parameter for PHP < 5.5

Hiranmoy Chatterjee

5 months ago

The following function may be useful to create columns from all values of indexed arrays:



Use:
-----


This will output:
-------------------
Array
[
    [0] => Array
        [
            [0] => A1
            [1] => B1
            [2] => C1
        ]

    [1] => Array
        [
            [0] => A2
            [1] => B2
            [2] => C2
        ]

    [2] => Array
        [
            [0] => A3
            [1] => B3
            [2] => C3
        ]

]

oleg dot bolden at gmail dot com

4 months ago

Index_key is safely applicable only in cases when corresponding values of this index are unique through over the array. Otherwise only the latest element of the array with the same index_key value will be picked up.



The above example will output:



To group values by the same `index_key` in arrays one can use simple replacement for the `array_column` like below example function:



The output:

Sbastien

4 months ago

The counterpart of array_column[], namely create an array from columns, can be done with array_map[] :

katrinaelaine6 at gmail dot com

5 years ago

array_column[] will return duplicate values.

Instead of having to use array_unique[], use the $index_key as a hack.

**Caution: This may get messy when setting the $column_key and/or $index_key as integers.**

Nolan chou

6 years ago

if [!function_exists['array_column']]
{
    function array_column[$input, $column_key=null, $index_key=null]
    {
        $result = array[];
        $i = 0;
        foreach [$input as $v]
        {
            $k = $index_key === null || !isset[$v[$index_key]] ? $i++ : $v[$index_key];
            $result[$k] = $column_key === null ? $v : [isset[$v[$column_key]] ? $v[$column_key] : null];
        }
        return $result;
    }
}

kaspar dot wilbuer at web dot de

6 years ago

If you need to extract more than one column from an array, you can use array_intersect_key on each element, like so:

function array_column_multi[array $input, array $column_keys] {
    $result = array[];
    $column_keys = array_flip[$column_keys];
    foreach[$input as $key => $el] {
        $result[$key] = array_intersect_key[$el, $column_keys];
    }
    return $result;
}

kiler129 @ nowhere

7 years ago

Please note this function accepts 2D-arrays ONLY, and silently returns empty array when non-array argument is provided.

Code:
class testObject {
    public $a = 123;
}
$testArray = [new testObject[], new testObject[], new testObject[]];
$result = array_column[$testArray, 'a']]; //array[0] { }

hypxm at qq dot com

7 years ago

a simple solution:

function arrayColumn[array $array, $column_key, $index_key=null]{
        if[function_exists['array_column ']]{
            return array_column[$array, $column_key, $index_key];
        }
        $result = [];
        foreach[$array as $arr]{
            if[!is_array[$arr]] continue;

            if[is_null[$column_key]]{
                $value = $arr;
            }else{
                $value = $arr[$column_key];
            }

            if[!is_null[$index_key]]{
                $key = $arr[$index_key];
                $result[$key] = $value;
            }else{
                $result[] = $value;
            }

        }

        return $result;
    }

marianbucur17 at yahoo dot com

7 years ago

If array_column is not available you can use the following function, which also has the $index_key parameter:

if [!function_exists['array_column']] {
    function array_column[$array, $column_key, $index_key = null]
    {
        return array_reduce[$array, function [$result, $item] use [$column_key, $index_key]
        {
            if [null === $index_key] {
                $result[] = $item[$column_key];
            } else {
                $result[$item[$index_key]] = $item[$column_key];
            }

            return $result;
        }, []];
    }
}

robbieaverill[at]gmail.com

7 years ago

Another option for older PHP versions [pre 5.5.0] is to use array_walk[]:

myles at smyl dot es

7 years ago

This didn't work for me recursively and needed to come up with a solution.

Here's my solution to the function:

if [ ! function_exists[ 'array_column_recursive' ] ] {
    /**
     * Returns the values recursively from columns of the input array, identified by
     * the $columnKey.
     *
     * Optionally, you may provide an $indexKey to index the values in the returned
     * array by the values from the $indexKey column in the input array.
     *
     * @param array $input     A multi-dimensional array [record set] from which to pull
     *                         a column of values.
     * @param mixed $columnKey The column of values to return. This value may be the
     *                         integer key of the column you wish to retrieve, or it
     *                         may be the string key name for an associative array.
     * @param mixed $indexKey  [Optional.] The column to use as the index/keys for
     *                         the returned array. This value may be the integer key
     *                         of the column, or it may be the string key name.
     *
     * @return array
     */
    function array_column_recursive[ $input = NULL, $columnKey = NULL, $indexKey = NULL ] {

        // Using func_get_args[] in order to check for proper number of
        // parameters and trigger errors exactly as the built-in array_column[]
        // does in PHP 5.5.
        $argc   = func_num_args[];
        $params = func_get_args[];
        if [ $argc < 2 ] {
            trigger_error[ "array_column_recursive[] expects at least 2 parameters, {$argc} given", E_USER_WARNING ];

            return NULL;
        }
        if [ ! is_array[ $params[ 0 ] ] ] {
            // Because we call back to this function, check if call was made by self to
            // prevent debug/error output for recursiveness :]
            $callers = debug_backtrace[];
            if [ $callers[ 1 ][ 'function' ] != 'array_column_recursive' ]{
                trigger_error[ 'array_column_recursive[] expects parameter 1 to be array, ' . gettype[ $params[ 0 ] ] . ' given', E_USER_WARNING ];
            }

            return NULL;
        }
        if [ ! is_int[ $params[ 1 ] ]
             && ! is_float[ $params[ 1 ] ]
             && ! is_string[ $params[ 1 ] ]
             && $params[ 1 ] !== NULL
             && ! [ is_object[ $params[ 1 ] ] && method_exists[ $params[ 1 ], '__toString' ] ]
        ] {
            trigger_error[ 'array_column_recursive[]: The column key should be either a string or an integer', E_USER_WARNING ];

            return FALSE;
        }
        if [ isset[ $params[ 2 ] ]
             && ! is_int[ $params[ 2 ] ]
             && ! is_float[ $params[ 2 ] ]
             && ! is_string[ $params[ 2 ] ]
             && ! [ is_object[ $params[ 2 ] ] && method_exists[ $params[ 2 ], '__toString' ] ]
        ] {
            trigger_error[ 'array_column_recursive[]: The index key should be either a string or an integer', E_USER_WARNING ];

            return FALSE;
        }
        $paramsInput     = $params[ 0 ];
        $paramsColumnKey = [ $params[ 1 ] !== NULL ] ? [string] $params[ 1 ] : NULL;
        $paramsIndexKey  = NULL;
        if [ isset[ $params[ 2 ] ] ] {
            if [ is_float[ $params[ 2 ] ] || is_int[ $params[ 2 ] ] ] {
                $paramsIndexKey = [int] $params[ 2 ];
            } else {
                $paramsIndexKey = [string] $params[ 2 ];
            }
        }
        $resultArray = array[];
        foreach [ $paramsInput as $row ] {
            $key    = $value = NULL;
            $keySet = $valueSet = FALSE;
            if [ $paramsIndexKey !== NULL && array_key_exists[ $paramsIndexKey, $row ] ] {
                $keySet = TRUE;
                $key    = [string] $row[ $paramsIndexKey ];
            }
            if [ $paramsColumnKey === NULL ] {
                $valueSet = TRUE;
                $value    = $row;
            } elseif [ is_array[ $row ] && array_key_exists[ $paramsColumnKey, $row ] ] {
                $valueSet = TRUE;
                $value    = $row[ $paramsColumnKey ];
            }

            $possibleValue = array_column_recursive[ $row, $paramsColumnKey, $paramsIndexKey ];
            if [ $possibleValue ] {
                $resultArray = array_merge[ $possibleValue, $resultArray ];
            }

            if [ $valueSet ] {
                if [ $keySet ] {
                    $resultArray[ $key ] = $value;
                } else {
                    $resultArray[ ] = $value;
                }
            }
        }

        return $resultArray;
    }
}

greensea

6 years ago

robsonvnasc at gmail dot com

5 years ago

Retrieve multiple columns from an array:

$columns_wanted = array['foo','bar'];
$array = array['foo'=>1,'bar'=>2,'foobar'=>3];

$filtered_array = array_intersect_key[array_fill_keys[$columns_wanted,'']];

//filtered_array
// array['foo'=>1,'bar'=>2];

coviex

7 years ago

Value for existing key in the resulting array is rewritten with new value if it exists in another source sub-array.

Dominik59

5 years ago

Presented function is good when You want to flatten nested array base on only one column, but if You want to flatten whole array You can use this method:

/**
     * Method that transforms nested array into the flat one in below showed way:
     * [
     *      [
     *          [0]=>'today',
     *      ],
     *      [
     *          [0]=>'is',
     *          [1]=>'very',
     *          [2]=>   [
     *                      [0]=>'warm'
     *                  ],
     *      ],
     * ]
     *
     * Into:
     *
     * ['today','is','very','warm']
     *
     * @param $input
     * @return array
     */
    private function transformNestedArrayToFlatArray[$input]
    {
        $output_array = [];
        if [is_array[$input]] {
            foreach [$input as $value] {
                if [is_array[$value]] {
                    $output_array = array_merge[$output_array, $this->transformNestedArrayToFlatArray[$value]];
                } else {
                    array_push[$output_array, $value];
                }
            }
        } else {
            array_push[$output_array, $input];
        }

        return $output_array;
    }

What is multidimensional array in PHP?

A multidimensional array is an array containing one or more arrays. PHP supports multidimensional arrays that are two, three, four, five, or more levels deep. However, arrays more than three levels deep are hard to manage for most people.

What is the multidimensional array?

A multidimensional array in MATLAB® is an array with more than two dimensions. In a matrix, the two dimensions are represented by rows and columns. Each element is defined by two subscripts, the row index and the column index.

How get key of multidimensional array in PHP?

Retrieving Values: We can retrieve the value of multidimensional array using the following method:.
Using key: We can use key of the associative array to directly retrieve the data value. ... .
Using foreach loop: We can use foreach loop to retrieve value of each key associated inside the multidimensional associative array..

What is multidimensional array example?

A multi-dimensional array is an array with more than one level or dimension. For example, a 2D array, or two-dimensional array, is an array of arrays, meaning it is a matrix of rows and columns [think of a table]. A 3D array adds another dimension, turning it into an array of arrays of arrays.

Chủ Đề