This question already has an answer here:
- CSV to Associative Array 5 answers
I have .txt file formatted as such:
"id","dealer_id","vin","stockno",
"1","2","3","4",
"5","6","7","8",
"9","10","11",12"
My goal is push this into an associative array like such:
"id"=>"1", "dealer_id"=>"2", "vin"=>"3", "stockno"=>"4"
My question is, the data loops through for every 4 entries. In the example above, I should have 3 arrays created like such:
"id"=>"1", "dealer_id"=>"2", "vin"=>"3", "stockno"=>"4"
"id"=>"5", "dealer_id"=>"6", "vin"=>"7", "stockno"=>"8"
"id"=>"9", "dealer_id"=>"10", "vin"=>"11", "stockno"=>"12"
How can I make this happen within PHP -- if possible at all?
Here's one approach:
<?php
$file = fopen('data.txt', 'r');
$headers = fgetcsv($file);
$result = array();
while ($row = fgetcsv($file)) {
if (!$row[0]) continue;
$nextItem = array();
for ($i = 0; $i < 4; ++$i) {
$nextItem[$headers[$i]] = $row[$i];
}
$result[] = $nextItem;
}
fclose($file);
var_dump($result);
This uses
fgetcsv
to read each delimited row of the file. The first row is used as the header names. Then, for each other row, we create a new entry and match the indexes to the header names. I set it to 4 because you have a trailing delimiter that creates an empty entry at the end, if you removed those from the input you could use the length of $headers
for the inner loop.
Here is the result of the
var_dump
for your data:array(3) {
[0]=>
array(4) {
["id"]=>
string(1) "1"
["dealer_id"]=>
string(1) "2"
["vin"]=>
string(1) "3"
["stockno"]=>
string(1) "4"
}
[1]=>
array(4) {
["id"]=>
string(1) "5"
["dealer_id"]=>
string(1) "6"
["vin"]=>
string(1) "7"
["stockno"]=>
string(1) "8"
}
[2]=>
array(4) {
["id"]=>
string(1) "9"
["dealer_id"]=>
string(2) "10"
["vin"]=>
string(2) "11"
["stockno"]=>
string(3) "12""
}
}
0 comments:
Post a Comment