【问题标题】:PHP CSV to Array with headings and id as group-keyPHP CSV 到数组,标题和 id 作为组键
【发布时间】:2021-03-27 20:58:26
【问题描述】:

我有一个 csv 文件,其中有标题。第一列有一个唯一的 id。

我使用以下代码输出数组和标题作为键:

function csv_to_array($filename='', $delimiter=',') {
    if(!file_exists($filename) || !is_readable($filename))
        return FALSE;

    $header = NULL;
    $data = array();
    if (($handle = fopen($filename, 'r')) !== FALSE)
    {
        while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
        {
            if(!$header)
                $header = $row;
            else
                $data[] = array_combine($header, $row);
        }
        fclose($handle);
        
    }
    return $data;
}

现在我得到了输出

Array
(
    [0] => Array
        (
            [id] => 2548
            [description ] => MyDescription
            [value] => 5
        )
    [1] => Array
        (
            [id] => 2549
            [description ] => MyDescription
            [value] => 10
        )

我想把“id”作为组数组的键

Array
(
    [2548] => Array
        (
            [id] => 2548
            [description ] => MyDescription
            [value] => 5
        )
    [2549] => Array

但我之前不能调用 id 一个组。

【问题讨论】:

    标签: php arrays csv


    【解决方案1】:

    您可以先获取 ID,然后将其作为索引放入 $data 数组中。是否要将 ID 保留在数据中?查看代码中的cmets

    function csv_to_array($filename='', $delimiter=',') {
        if(!file_exists($filename) || !is_readable($filename))
            return FALSE;
    
        $header = NULL;
        $data = array();
        if (($handle = fopen($filename, 'r')) !== FALSE)
        {
            while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
            {
                if(!$header)
                    $header = $row;
                else{
                    $id = $row[0]; // grab the ID from the row / expectiong that the ID is in the first column of your CSV
                    //unset($row[0]); // <-- uncomment this line if you want to remove the ID from the data array
                    $data[$id] = array_combine($header, $row);
                }
                    
            }
            fclose($handle);
    
        }
        return $data;
    }
    

    【讨论】:

    • 哦,非常感谢,一切正常!取消设置id的可能性也非常有用!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 2018-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多