I am uploading a csv file and then parsing it using str_getcsv. All works great except that I need a way to cycle through them. Ideally, it'd be great to have the array come back and look like this:
Array (
[1] => Array
(
[0] => 1 // first id in csv
[1] => name
[2] => address
[3] => town
[4] => state
[5] => zip
[6] => phone
[7] => website
[8] => other
[9] => other
)
[22] => Array
(
[10] => name
[11] => address
[12] => town
[13] => state
[14] => zip
[15] => phone
[16] => website
[17] => other
[18] => other
)
[24] => Array
(
[19] => name
[20] => address
[21] => town
[22] => state
[23] => zip
[24] => phone
[25] => website
[26] => other
[27] => other
)
)
However the data comes back like the following:
Array
(
[0] => 1 // first id in csv
[1] => name
[2] => address
[3] => town
[4] => state
[5] => zip
[6] => phone
[7] => website
[8] => other
[9] => other
22 // id field
[10] => name
[11] => address
[12] => town
[13] => state
[14] => zip
[15] => phone
[16] => website
[17] => other
[18] => other
24// id field
[19] => name
[20] => address
[21] => town
[22] => state
[23] => zip
[24] => phone
[25] => website
[26] => other
[27] => other
Any suggestions on how to fix this to look like the array at the top? right now I'm doing:
$csvfile = file_get_contents($targetFile);
$csv = str_getcsv($csvfile);
str_getcsv() expects the string passed as parameter to be one record.
But since your source is a file anyway the easiest way is probably to use fgetcsv() instead of str_getcsv()
self-contained example:
prints
edit2: For using the first element of each record as the key in the result array:
Well, just count the number of items an entry has then make a loop inside a loop
That is what I just did and works very well.
Not the pretties thing on this world but I think it works.
result of the code:
Hope this helps