使用CSV文件的键值对创建php数组 [英] Create php array with key value pair for an csv file

查看:79
本文介绍了使用CSV文件的键值对创建php数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在控制器操作中导入了一个csv文件。 CSV文件的结构如下所示。

I have import a csv file in my controller action. The structure of csv file is like given below.

Name , Phone , address
user1 , 99887766 , xyz 
user2, 99885566 , hjj 

现在我要使用csv标头信息作为键和行的数组数组数据作为价值。

Now I want array of arrays with csv header information as key and row data as value. The required output should be something like this.

[
"0" => [ "Name" => "user1" , "Phone" => "99887766" , "address" => "xyz" ],
"1" => [ "Name" => "user2" , "Phone" => "99885566" , "address" => "hjj" ],
]

我能够用php爆炸获取行数据。问题在于将密钥设置为给定的标头。
谁能帮我这个忙。

I am able to get the row data with php explode. The problem is in setting the key as header given. Can anyone help-me for this.

推荐答案

您可以尝试以下代码

 $rows = file($csv_data_file);
 $header = array_shift($rows); //get the header out
 $header = explode(",", $header);
 $final_array = array();
 foreach ($rows as $row) {
      $row = explode(",", $row);
      $final_array[] = array($header[0] => $row[0], $header[1] => $row[1], $header[2] => $row[2]);
 }

这篇关于使用CSV文件的键值对创建php数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆