- if (!function_exists (' Array_column ')) {
- function Array_column ($input, $columnKey, $indexKey =null) {
- $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;
- }
- }//Bbs.it-home.org
- $result [$key] = $tmp;
- }
- return $result;
- }
- }
- Examples of Use
- $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 '
- )
- );
- $firstNames = Array_column ($records, ' first_name ');
- Print_r ($firstNames);
- /*
- Array
- (
- [0] = John
- [1] = Sally
- [2] = Jane
- [3] = Peter
- )
- */
- $records = Array (
- Array (1, ' John ', ' Doe '),
- Array (2, ' Sally ', ' Smith '),
- Array (3, ' Jane ', ' Jones ')
- );
- $lastNames = Array_column ($records, 2);
- Print_r ($lastNames);
- /*
- Array
- (
- [0] = = Doe
- [1] = Smith
- [2] = Jones
- )
- */
- $mismatchedColumns = Array (
- Array
- ' A ' = ' foo ',
- ' B ' = ' bar ',
- ' E ' = ' baz '
- ),
- Array
- ' A ' = ' qux ',
- ' C ' = ' Quux ',
- ' d ' = ' corge '
- ),
- Array
- ' A ' = ' grault ',
- ' B ' = ' garply ',
- ' E ' = ' Waldo '
- ),
- );
- $foo = Array_column ($mismatchedColumns, ' A ', ' B ');
- Print_r ($foo);
- /*
- Array
- (
- [Bar] = foo
- [0] = Qux
- [Garply] = Grault
- )
- */
Copy Code |