eveo
eveo

Reputation: 2843

Parsing a CSV file into a two dimensional array

my goal of this is to put the first index (first value of each line in the csv) into a dropdown html select list.

test.csv

mark, blue, tall,
mike, black, short

index.php

<?php
$handle = fopen("csv/food.csv", "r");

while (($data = fgetcsv($handle, 5000, ",")) !== FALSE) {
    echo "<pre>";
    print_r($data);
    echo "<pre>";
}
?>

output

Array
(
    [0] => mark
    [1] => blue
    [2] => tall
    [3] => mike
    [4] => black
    [5] => short
)

output if I remove comma after tall

Array
(
    [0] => mark
    [1] => blue
    [2] => tall
mike
    [3] => black
    [4] => short
)

desired output

Array
(
    [0][0] => mark
    [0][1] => blue
    [0][2] => tall
    [1][0] => mike
    [1][1] => black
    [1][2] => short
)

Upvotes: 0

Views: 1493

Answers (1)

eveo
eveo

Reputation: 2843

Got it working:

<select name="list" > 
<?php 
$file = fopen("food.csv", "r"); 

while (!feof($file) ) { 
    $lines = fgetcsv($file, 1024);?> 
    <option value="<?php print $lines[0] ?>"> <?php print $lines[0] ?> </option> 
<?php } ?>
</select>
<?php 
fclose($file); 
?>

Upvotes: 2

Related Questions