我有一个这样的数组:
$arr = array ( array ( "id" => 1,
"name" => "John",
"age" => 22 ),
array ( "id" => 2,
"name" => "Jack",
"age" => 30 ),
array ( "id" => 3,
"name" => "Peter",
"age" => 14 )
);
现在我需要删除所有数组的项目名称并保留它们的值,如下所示:
$newarr = array ( array ( 1, "John", 22 ),
array ( 2, "Jack", 30 ),
array ( 3, "Peter", 14 )
);
这样做可能吗?
注意到我这样做的意图是根据该数组创建一个.CSV
文件。
以下是我的完整代码:
public function export(Request $request){
header('Content-Type: application/excel');
header('Content-Disposition: attachment; filename="export.csv"');
$tb_name_alias = $request->tb_name;
$convert_alias_to_table_name = array('person' => "App\\persons");
$tb_name = $convert_alias_to_table_name[$tb_name_alias];
$arr = $tb_name::all()->toArray();
// here I need to remove all array's item names (I think)
$fp = fopen('php://output', 'w');
foreach ( $arr as $line ) {
$val = explode(",", $line);
fputcsv($fp, $val);
}
fclose($fp);
}
注意:这也适用:
public function export(Request $request){
header('Content-Type: application/excel');
header('Content-Disposition: attachment; filename="export.csv"');
$arr = array(
'1,John,22',
'2,Jack,30',
'3,Peter,14'
);
$fp = fopen('php://output', 'w');
foreach ( $arr as $line ) {
$val = explode(",", $line);
fputcsv($fp, $val);
}
fclose($fp);
}
答案 0 :(得分:2)
使用fputcsv http://php.net/manual/en/function.fputcsv.php
它不关心关键值
如果您真的想要删除密钥。循环并在数组的结果上调用array_values
答案 1 :(得分:1)
使用array_map
-
$newArr = array_map('array_values', $arr);
答案 2 :(得分:1)
您可以使用array_values
而不是删除这样的名称:
$fp = fopen('php://output', 'w');
foreach ( $arr as $item) {
$values = array_values($item);
fputcsv($fp, $values);
}
fclose($fp);