-
- 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;
- }
- }
-
- // 使用例子
- $records = array(
- array(
- 'id' => 2135,
- 'first_name' => 'John',
- 'last_name' => 'Doe'
- ),
- array(
- 'id' = > 3245,
- 'first_name' => 'サリー',
- 'last_name' => 'スミス' ),
- array(
- 'id' => 'first_name' => 'ジェーン' ,
- 'last_name' => 'ジョーンズ'
- ),
- array(
- 'id' => 5623,
- 'first_name' => 'ピーター',
- 'last_name' => 'Doe'
- )
- );
- $firstNames = array_column($records, 'first_name');
- print_r($firstNames);
- /*
- Array
- (
- [0] => ジョン
- [1] => サリー
- [2] => ジェーン
- [3] => ピーター
- )
- */
-
- $records = array(
- array(1, 'ジョン', 'Doe'),
- array(2, 'サリー', 'スミス' ),
- array(3, 'Jane', 'Jones')
- );
- $lastNames = array_column($records, 2);
- print_r($lastNames);
- /*
- Array
- (
- [0] => ; ドウ
- [1] =>スミス
- [2] => Jones
- )
- */
-
- $mismatchedColumns = array(
- array(
- 'a' => 'foo',
- 'b' => 'bar',
- 'e' => 'baz'
- ) ,
- array(
- 'a' => 'qux',
- 'c' => 'qux',
- '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
- )
- */
-
-
复制發
|