如何将每个单列数据从php多维数据转换为单列数组?
like $_test = = array(
array(
'id' => 1001,
'first_name' => 'kalpesh',
'last_name' => 'gamit',
),
array(
'id' => 1002,
'first_name' => 'kartik',
'last_name' => 'patel',
),
array(
'id' => 2002,
'first_name' => 'smith',
'last_name' => 'Jones',
),
array(
'id' => 4004,
'first_name' => 'patel',
'last_name' => 'Doe',
)
);
只需要像id或first_name这样的结果,而不使用while,foreach等等的使用循环
Array
(
[0] => 1001
[1] => 1002
[2] => 2002
[3] => 4004
)
答案 0 :(得分:2)
如下所示更新您的脚本并检查它,但它仅适用于 PHP 5.5大于仅版本 ...
$_test = = array(
array(
'id' => 1001,
'first_name' => 'kalpesh',
'last_name' => 'gamit',
),
array(
'id' => 1002,
'first_name' => 'kartik',
'last_name' => 'patel',
),
array(
'id' => 2002,
'first_name' => 'smith',
'last_name' => 'Jones',
),
array(
'id' => 4004,
'first_name' => 'patel',
'last_name' => 'Doe',
)
);
$ids_only = array_column($records, 'id');
print_r($ids_only);
ID
的结果Array
(
[0] => 1001
[1] => 1002
[2] => 2002
[3] => 4004
)
first_name的结果
$first_name = array_column($records, 'id');
print_r($first_name);
Array
(
[0] => Kalpesh
[1] => kartik
[2] => smith
[3] => patel
)
运行上面的PHP脚本,请检查....
答案 1 :(得分:0)
您可以使用 array_map :
$id_list = array_map(function($var) {
return $var['id'];
}, $_test);