Php returns a specified column in the array (php5.5.0 default function array_column () in php & amp; lt; 5.5.0 application)
Array_column () returns the column with the specified key name in the array. (PHP 5> = 5.5.0) Array_column-returns a specified column in the array. Php Reference: http://www.php.net/manual/zh/function.array-column.php
What if php version is earlier than 5.5.0? We customize The following code is taken from onethink.
- /**
- * Returns a specified column in the array.
- * Http://www.onethink.cn
- */Application/Common/function. php
- *
- * Array_column-PHP 5> = 5.5.0 default function
- * PHP 5 <5.5.0 uses a user-defined function
- *
- * @ Access public
- * @ Param array $ input needs to retrieve the multi-dimensional array (or result set) of the array column)
- * @ Param string $ columnKey the column to be returned. it can be the index of the index array or the key of the column associated with the array. It can also be NULL. at this time, the entire array will be returned (it works very well when the indexKey parameter is used to reset the array key)
- * @ Param string $ indexKey is the index/key column of the returned array. it can be an integer index of the column or a 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;
- }
- }
- // 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 );
- ?>
- Array
- (
- [0] => John
- [1] => Sally
- [2] => Jane
- [3] => Peter
- )
|