将csv列放入数组 [英] putting csv column into an array

查看:116
本文介绍了将csv列放入数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个csv与列标题:description,stock,mfgid(和一些其他标题,我不需要)。



来自列标题库的数据和数组中的mfgid。



我使用fgetcsv(),但是它把整个行放入数组的一个排他键。 p>

在stackoverflow上找到了,但是无法正常工作:

  $ file = fopen('inventory.csv','r'); 
while(($ line = fgetcsv($ file))!== FALSE){
// $ line是csv元素的数组
print_r($ line);
}
fclose($ file);


解决方案

要读取完整的CSV文件,

  $ csv = array_map(str_getcsv,file(inventory.csv)); 
$ header = array_shift($ csv);

这将 $ header 数组从 $ csv 数据的其余部分中删除。



字段,请尝试:

  $ col1 = array_search(stock$ headers); 
$ col2 = array_search(mfgid,$ headers);
foreach($ csv as $ row){
$ map [$ row [$ col1]] = $ row [$ col2]; }

这将给你一个股票 > mfgid 数组。


I've got a csv with column headers: description, stock, mfgid (and some other headers I don't need).

I need to get the data from the column headers stock and mfgid in an array.

I was using fgetcsv() but it was putting the entire row into an exclusive key in the array.

found this here at stackoverflow but can't get it to work right:

$file = fopen('inventory.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
  //$line is an array of the csv elements
  print_r($line);
}
fclose($file);

解决方案

For reading in a complete CSV file use this construct:

$csv = array_map("str_getcsv", file("inventory.csv"));
$header = array_shift($csv);

This separates the $header into a separate array from the rest of the $csv data.

If you then (seemingly?) want a map of two fields, try:

$col1 = array_search("stock" $headers);
$col2 = array_search("mfgid", $headers);
foreach ($csv as $row) {
     $map[ $row[$col1] ] = $row[$col2]; }

This would give you a stock -> mfgid array.

这篇关于将csv列放入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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