if(!function_exists('array_
column'))
{ function array_
column($input,$
columnKey,$indexKey=null)
{ $
columnKeyIs
number = (is_numeric($
columnKey)) ? true :
false;
$indexKeyIsNull = (is_null($indexKey)) ? true :
false;
$indexKeyIs
number = (is_numeric($indexKey)) ? true :
false;
$result = array(
); foreach((array)$input as $key=>$row)
{ if($
columnKeyIs
number)
{ $tmp = array_slice($row,1
); $tmp = (is_array($tm
p) && !empty($tm
p)) ? current($tm
p) : null;
}else
{ $tmp = isset($row[$
columnKe
y]) ? $row[$
columnKey] : null;
}
if(!$indexKeyIsNull)
{ if($indexKeyIs
number)
{ $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[$indexKe
y]) ? $row[$indexKey] : 0;
}
}
$@R_
675_5272@$key] = $tmp;
}
return $result;
}
} // 使用例子
$records = array(
array(
'id' => 2135,
'firs
t_name' => 'John',
'las
t_name' => 'Doe'
),
array(
'id' => 3245,
'firs
t_name' => 'Sally',
'las
t_name' => 'Smith'
),
array(
'id' => 5342,
'firs
t_name' => 'Jane',
'las
t_name' => 'Jo
nes'
),
array(
'id' => 5623,
'firs
t_name' => '
Peter',
'las
t_name' => 'Doe'
)
); $firstNames = array_
column($records,'firs
t_name'
); print_r($firstNames
); /*
Array
(
[0] => John
[1] => Sally
[2] => Jane
[3] =>
Peter )
*/$records = array(
array(1,'John','Doe'),
array(2,'Sally','Smith'),
array(3,'Jane','Jo
nes')
); $lastNames = array_
column($records,2
); print_r($lastNames
); /*
Array
(
[0] => Doe
[1] => Smith
[2] => Jo
nes )
*/$mi
smatched
columns = array(
array(
'a' => 'foo',
'b' => 'bar',
'e' => 'baz'
),
array(
'a' => 'qux',
'c' => 'quux',
'd' => 'corge'
),
array(
'a' => 'grault',
'b' => 'garply',
'e' => 'waldo'
),
); $foo = array_
column($mi
smatched
columns,'a','b'
); print_r($foo
); /*
Array
(
[bar] => foo
[0] => qux
[garply] => grault
)
*/
php// Array represen
Ting a possible record set returned from a database
$records = array(
array(
'id' => 2135,
'las
t_name' => 'Doe',
),
array(
'id' => 3245,
'las
t_name' => 'Smith',
array(
'id' => 5342,
'las
t_name' => 'Jo
nes',
array(
'id' => 5623,
)
);$firs
t_names = array_
column($records,'firs
t_name'
);print_r($firs
t_names
);?>
Array
(
[0] => John
[1] => Sally
[2] => Jane
[3] =>
Peter)
php// Using the $records array from Example #1
$las
t_names = array_
column($records,'las
t_name','id'
);print_r($las
t_names
);?>
Array
(
[213
5] => Doe
[324
5] => Smith
[5342] => Jo
nes [5623] => Doe
)