读取没有标题行的csv文件,并将其转换为关联数组的索引数组



我正试图从一个文本文档中创建几个数组。

文本文档的格式为

"1","July 1999"," 2,782,546 "," $17.38 "," $338,545.98 "," 3,004 ",""
"2","August 1999"," 2,739,441 "," $18.68 "," $153,343.98 "," 3,023 ",""
"3","September 1999"," 2,650,431 "," $20.86 "," $308,929.17 "," 3,042 ",""

我需要创建几个数组,将日期与另一个字段相结合,例如:

$Array1 = array("July 1999"=> " 2,782,546 ", "August 1999"=> " 2,739,441 ", "September 1999"=> "2,650,431 ");
$Array2 = array("July 1999"=> " $17.38 ", "August 1999"=> " $18.68 ", "September 1999"=> "$20.86 ");

我不知道如何正确地解析字符串以准确地创建数组。

目前尚不清楚您需要多大的灵活性(数据的日期/数量是否是动态的(,但您实际上需要解析csv文件行并转换数据。

(我会像你一样使用fopen()fgetcsv(),但我不能在沙箱中使用。(

代码:(演示(

$csv = <<<TXT
"1","July 1999"," 2,782,546 "," $17.38 "," $338,545.98 "," 3,004 ",""
"2","August 1999"," 2,739,441 "," $18.68 "," $153,343.98 "," 3,023 ",""
"3","September 1999"," 2,650,431 "," $20.86 "," $308,929.17 "," 3,042 ",""
TXT;
$data = [];
// extract the csv data
foreach (
array_map('str_getcsv', explode("nn", $csv))
as
$row
) {
$data[$row[1]] = array_slice($row, 2, -1);
}
$result = [];
// transpose and trim
foreach ($data as $k => $row) {
foreach ($row as $i => $v) {
$result[$i][$k] = trim($v);
}
}
var_export($result);

我能够用这段代码解析出我需要的数据。

$row = 1;
if (($handle = fopen("file.txt", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$row++;
for ($c = 1; $c < 2; $c++) {
for ($d = 2; $d<3;$d++){ 
echo $data[$c] . " " . $data[$d] . "<br />n" ;
}
}
}
}
fclose($handle);

相关内容

  • 没有找到相关文章

最新更新