php array_column
阿新 • • 發佈:2018-12-16
* 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) { // (PHP 4 >= 4.0.6, PHP 5, PHP 7) // array_map — Applies the callback to the elements of the given arrays return myarraymap(function($item) use ($col) { return $item[$col]; }, $a); } // 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);
* test
$ php mypluck.php Array ( [0] => John [1] => Sally [2] => Jane [3] => Peter )