我读了一个 csv 文件并得到了这个数组 $rowsArray( [0] => Array ( [0] => Name [1] => Company [2] => Email [3] => City )[1] => Array ( [0] => Foo [1] => Foo & co [2] => foo@mail.com [3] => NY )[2] => Array ( [0] => Bar [1] => Bar & co [2] => bar@mail.com [3] => Las Vegas ))我会尝试通过仅过滤第一个数组中包含的某些字段来将其转换为关联数组。结果应该是这样Array([0] => Array ( ['Name'] => Foo ['Company'] => Foo & co ['Email] => foo@mail.com ) [1] => Array ( ['Name'] => Bar ['Company'] => Bar & co ['Email] => bar@mail.com ))不幸的是,我以各种方式尝试过,但没有成功。$name = array_search('Name', $rows[0]);$company = array_search('Company', $rows[0]);$email = array_search('Email', $rows[0]);$rows = unset($rows[0]);$array = array();foreach ( $rows as $r => $row ) { foreach ( $row as $c => $cell ) { if ($c == $name) { $array = array( 'name' => $cell ); } if ($c == $company) { $array = array( 'company' => $cell ); } if ($c == $email) { $array = array( 'email' => $cell ); } }}你能给我一些建议吗?谢谢
2 回答
白衣染霜花
TA贡献1796条经验 获得超10个赞
你可以试试下面的代码。它将基于 csv 文件使该动态的标题名称和值。
$header = array();
foreach($array as $key=>$value){
if($key == 0){
$header = array_values($value);
}else{
$final_result[]= array_combine($header, array_values($value));
}
}
echo "<pre>";
print_r($final_result);
小怪兽爱吃肉
TA贡献1852条经验 获得超1个赞
在阅读文件时尝试构建您想要的内容,而不必重新排列您一开始不想要的内容。
// loose the titles line
fgetcsv($file, 1000, ',')
$rows= [];
while ( $line = fgetcsv($file, 1000, ',') !== FALSE) {
$rows[] = ['Name'=> $line[0], 'Company'=> $line[1], 'Email'=> $line[2] ];
}
- 2 回答
- 0 关注
- 170 浏览
添加回答
举报
0/150
提交
取消