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



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

im使用以下代码输出arays和标题作为关键字:

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称为一组。

您可以先获取ID,然后将其作为索引放入$data数组中。您想在数据中保留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{
$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;
}

最新更新