使用 PHP 将 CSV 值解析为地图
如果我的文本文件是
Jack Jones;batter;100;
Bobby Brown;bowler;90;
我知道如何将它们放入数组中,但是如何将它们放入带有键的数组中?例如,在我读取文本文件后,我的数组将是 -
$player1 = ('name' => 'Jack Jones', 'skill' => 'batter', 'points' => '100');
$player2 = ('name' => 'Bobby Brown', 'skill' => 'bowler', 'points' => '90');
// therefore -
echo $player1['name']; #This would output the name 'Jack Jones'
If my text file is
Jack Jones;batter;100;
Bobby Brown;bowler;90;
I know how to get them into an array but how would I get them into an array with Keys? For example, after I read the text file my array would be -
$player1 = ('name' => 'Jack Jones', 'skill' => 'batter', 'points' => '100');
$player2 = ('name' => 'Bobby Brown', 'skill' => 'bowler', 'points' => '90');
// therefore -
echo $player1['name']; #This would output the name 'Jack Jones'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不能直接这样做,因为文本文件中没有有关列名称的信息。但如果您知道如何获得此:
并且列名称是固定的,您可以设置包含键的第二个数组:
然后使用 array_combine 以获得您想要的结果:
you can't directly as there's no information about column names in the text file. but if you know how to get this:
and the column names are fixed, you could set up a second array containing the keys:
and then use array_combine to get your desired result:
您如何解析 CSV 文件?
您使用 CsvReader 类吗?
在这种情况下,您可以执行以下操作:
希望这会有所帮助。
How do you parse your CSV file?
Do you use the Class CsvReader ?
In this case you can do something like:
hope this helps.