1

ok so ive been trying to get this to work for hours now and cant figure it out. Ive got a csv file in the format of

item 1, item 1 stuff
item 2, item 2 stuff
item 3, item 3 stuff
item 4, item 4 stuff

and im trying to parse it into an array using fgetscsv.

$file = fopen('test.csv', 'r');
    while (($MyCSVArray = fgetcsv($file)) !== FALSE) {

    print_r($MyCSVArray);
}
fclose($file);

I would really rather parse it into an associative array so i can index it like so

MyCSVArray[item 1]

which would output

item 1 stuff

However the problem I am having is that since there isnt a comma after every value it groups item 1 stuff with item 2 like so

MyCSVArray[0] = item 1
MyCSVArray[1] = item 1 stuff item 2
MyCSVArray[2] = item 2 stuff item 3

Maybe I dont understand csv files or the csv function, but I really need this to work the way I want and dont understand how to make it work and am about to smash my face into my keyboard.

1 Answer 1

1

Just read the data like you are and set the value into a new associative array as desired

$new_array = array()
$file = fopen('test.csv', 'r');
while (($MyCSVArray = fgetcsv($file)) !== FALSE) {
    $new_array[$MyCSVArray[0]] = $MyCSVArray[1];
}
fclose($file);

var_dump($new_array);

To the second part of your problem, it seems like you might not have proper end of line characters in your file if items from the next row are being grouped with the items from previous row.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the reply. hmm. Im exporting the data from an excel file to a csv. I would think the end of line characters would be there. But maybe not
ok figured it out. I had opened the csv file in my text editor and when I did that i guess it stripped those new line characters. works just fine now. thanks for your help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.