将CSV文件解析为二维数组

时间:2013-01-02 12:32:26

标签: php arrays parsing csv

我的目标是将第一个索引(csv中每行的第一个值)放入下拉列表html select列表中。

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>";
}
?>

输出

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

输出如果我删除高后的逗号

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

所需的输出

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

1 个答案:

答案 0 :(得分:2)

搞定了:

<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); 
?>