简体   繁体   English

PHP CSV 到以标题和 id 作为组键的数组

[英]PHP CSV to Array with headings and id as group-key

i have a csv-file where i have headings.我有一个 csv 文件,其中有标题。 the first column has a unique id.第一列有一个唯一的 id。

im using following code for the output in arays and headings as keys:我在数组和标题中使用 output 的以下代码作为键:

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

Now i get the output现在我得到了 output

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

i want to put the "id" as key for the group array like我想把“id”作为组数组的键,比如

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

but i cant call the id one group before.但我之前不能将 id 称为一组。

You can just grab the ID first an put it into the $data array as an index.您可以先获取 ID,然后将其作为索引放入$data数组中。 Do you want to keep the ID in the data?是否要将 ID 保留在数据中? See the comments in the code查看代码中的注释

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM