How do I make the columns of a CSV as arrays with the header being the key in PHP

时间:2017-06-12 17:08:43

标签: php arrays csv foreach

I have a csv file which I need to extract data from us use. I need to create an individual array from each column so:

example table

I need heading1 as the key and the values as data1, data2, data3.

I guess I need the key so I can access a particular column.

2 个答案:

答案 0 :(得分:0)

You can use the str_getcsv() function.

答案 1 :(得分:0)

您可以获取第一行,然后在迭代后续行时使用array_combine,以使用标题行中的值作为数组键。

$file = fopen('yourfile.csv', 'r');

$keys = fgetcsv($file);   // get the headers

while (false !== ($values = fgetcsv($file))) {
    $row = array_combine($keys, $values);   // combine headers with values
    // now you can do
    $value = $row['heading1']; //etc.

}
相关问题