-
-
Save akadata/61bf299ae40438d752b0c052d73e8e72 to your computer and use it in GitHub Desktop.
Implementation of array_column function for PHP 5.3+, support for array of objects is also provided.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Implementation of array_column function for PHP 5.3+, support for array of objects is also provided. | |
* | |
* @param array $input | |
* @param mixed $column_key | |
* @param mixed $index_key | |
* @return array | |
* @see http://php.net/manual/en/function.array-column.php | |
*/ | |
function arrayColumn($input, $column_key, $index_key = null) | |
{ | |
if (func_num_args() < 2) { | |
trigger_error('array_column() expects at least 2 parameters, '.func_num_args().' given', E_USER_WARNING); | |
return null; | |
} elseif (!is_array($input)) { | |
trigger_error('array_column() expects parameter 1 to be array, '.gettype($input).' given', E_USER_WARNING); | |
return null; | |
} | |
if ($index_key) { | |
return array_combine( | |
arrayColumn($input, $index_key), | |
arrayColumn($input, $column_key) | |
); | |
} | |
// 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. | |
foreach ($input as $key => $val) { | |
if (is_object($val) && !in_array($column_key, get_object_vars($val)) && | |
(!method_exists($val, '__get') || !method_exists($val, '__isset'))) { | |
unset($input[$key]); | |
} | |
} | |
$input_count = count($input); | |
return array_map( | |
function ($element, $column_name) { | |
if (is_object($element)) { | |
return $element->{$column_name}; | |
} | |
return $element[$column_name]; | |
}, | |
$input, | |
$input_count ? array_fill(0, $input_count, $column_key) : array() | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment