* mypluck.php
<?php
// array_column(PHP 5>=5.5.0, PHP 7)
// http://php.net/manual/en/function.array-column.php
function myarraymap(callable $f, array $a) : array {
$ret = [];
for ($i = 0, $n = count($a); $i < $n; $i++) {
$ret[$i] = $f($a[$i], $i);
}
return $ret;
}
function mypluck(array $a, string $col, string $key="") : array {
// (PHP 4 >= 4.0.6, PHP 5, PHP 7)
// array_map — Applies the callback to the elements of the given arrays
if (empty($key)) {
return myarraymap(function($item) use ($col) {
return $item[$col];
}, $a);
}
$ret = [];
for ($i = 0, $n = count($a); $i < $n; $i++) {
$ret[ $a[$i][$key] ] = $a[$i][$col];
}
return $ret;
}
// 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 = mypluck($records, 'first_name');
print_r($first_names);
$last_names = mypluck($records, 'last_name', 'id');
print_r($last_names);
* test
$ php mypluck.phpArray
(
[0] => John
[1] => Sally
[2] => Jane
[3] => Peter
)
Array
(
[2135] => Doe
[3245] => Smith
[5342] => Jones
[5623] => Doe
)