Skip to content

Instantly share code, notes, and snippets.

@akadata
Forked from debuss/arrayColumn.php
Created December 16, 2019 21:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akadata/61bf299ae40438d752b0c052d73e8e72 to your computer and use it in GitHub Desktop.
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.
<?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