php函数之fgetcsv

原创
2016/10/17 09:53
阅读数 50
// items.csv
/*
id,name,price
1,one,1.1
2,two,2.2
3,three,3.3
*/
// 解析为:
/*
Array
(
    [0] => Array
        (
            [id] => 1
            [name] => one
            [price] => 1.1
        )

    [1] => Array
        (
            [id] => 2
            [name] => two
            [price] => 2.2
        )

    [2] => Array
        (
            [id] => 3
            [name] => three
            [price] => 3.3
        )

)
*/
// code
<?php
$file = __DIR__ . '/items.csv';

$fp = fopen($file, 'r');

$items = [];
$keys = null;

while (($data = fgetcsv($fp)) !== false) {
    if ($data[0] == 'id') {
        $keys = $data;
    } else {
        $items[] = array_combine($keys, $data);
    }
}

fclose($fp);

print_r($items);

 

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
0 评论
0 收藏
0
分享
返回顶部
顶部