array_column() returns the column with the specified key name in the array (PHP 5 >= 5.5.0) array_column — returns a column specified in the array php reference manual: http://www.php.net/manual/zh/function .array-column.php
What to do if the php version is less than 5.5.0? Let’s customize one The following code is taken from onethink
- /**
- * Returns a specified column in the array
- * http://www.onethink.cn
- * /Application/Common/Common/function.php
- *
- * array_column — PHP 5 >= 5.5.0 default function
- * PHP 5 < 5.5.0 uses custom functions
- *
- * @access public
- * @param array $input The multi-dimensional array (or result set) of the array column that needs to be taken out
- * @param string $columnKey The column that needs to return the value, It can be a column index of an index array, or a key of a column of an associative array. It can also be NULL, in which case the entire array will be returned (very useful when used with the indexKey parameter to reset the array key)
- * @param string $indexKey is the index/key column of the returned array, it can be an integer of the column Index, or string key value.
- * @return array
- */
- if (! function_exists('array_column'))
- {
- function array_column(array $input, $columnKey, $indexKey = null)
- {
- $result = array() ;
- if (null === $indexKey)
- {
- if (null === $columnKey)
- {
- $result = array_values($input);
- }
- else
- {
- foreach ($input as $row)
- {
- $result[] = $row[$columnKey];
- }
- }
- }
- else
- {
- if (null === $columnKey)
- {
- foreach ($input as $row)
- {
- $ result[$row[$indexKey]] = $row;
- }
- }
- else
- {
- foreach ($input as $row)
- {
- $result[$row[$indexKey]] = $row[$columnKey] ;
- }
- }
- }
- return $result;
- }
- }
Copy code
- // Array representing a possible record set returned from a database
- $records = array(
- array(
- 'id' => 2135,
- 'first_name' => 'John' ,
- 'last_name' => 'Doe',
- ),
- array(
- 'id' => 3245,
- 'first_name' => 'Sally',
- 'last_name' => 'Smith',
- ),
- array(
- 'id' => 5342,
- 'first_name' => 'Jane',
- 'last_name' => 'Jones',
- ),
- array(
- 'id' => 5623 ,
- 'first_name' => 'Peter',
- 'last_name' => 'Doe',
- )
- );
-
- $first_names = array_column($records, 'first_name');
- print_r($first_names);
- ?>
Copy code
- Array
- (
- [0] => John
- [1] => Sally
- [2] => Jane
- [3] => Peter
- )
Copy code
|