![](/img/trans.png)
[英]PHP CSV to associative array with top row as keys and following rows as values
[英]PHP CSV to associative array with top row as keys and columns as value arrays
我正在嘗試使用CSV文件創建多維數組,例如:
“ a”,“ b”,“ c”
1,2,3
4,5,6
將返回為:
array(
'a' => array(1, 4),
'b' => array(2, 5),
'c' => array(3, 6),
)
但是我有代碼:
<?php
function readCSV($csvFile) {
$aryData = [];
$header = NULL;
$handle = fopen($csvFile, "r");
if($handle){
while (!feof($handle)){
$aryCsvData = fgetcsv($handle);
if(!is_array($aryCsvData)){
continue;
}
if(is_null($header)){
$header = $aryCsvData;
}
elseif(is_array($header) && count($header) == count($aryCsvData)){
$aryData[] = array_combine($header, $aryCsvData);
}
}
fclose($handle);
}
return $aryData;
}
print_r(readCSV("Book1.csv"));
?>
返回為:
Array(
[0] => Array ( [a] => 1 [b] => 2 [c] => 3 )
[1] => Array ( [a] => 4 [b] => 5 [c] => 6 )
)
將不勝感激!
而不是隨便構建結束數組。 此代碼在循環之前讀取標題行,然后僅將所有數據線讀取到另一個數組中。 然后將頭數組的每個元素與數據數組中的匹配列組合在一起(使用array_column()
和頭元素的位置)...
function readCSV($csvFile) {
$aryData = [];
$output = [];
$header = NULL;
$handle = fopen($csvFile, "r");
if($handle){
$header = fgetcsv($handle);
while ($aryData[] = fgetcsv($handle));
foreach ( $header as $key=>$label) {
$output[$label] = array_column($aryData, $key);
}
fclose($handle);
}
return $output;
}
讀取文件的第一行,並創建帶有空列的關聯數組。 然后讀取每個剩余的行並遍歷整個行,將值推入列數組。
<?php
function readCSV($csvFile) {
$aryData = [];
$handle = fopen($csvFile, "r");
if($handle){
$headerRow = fgetcsv($handle);
if (!$headerRow) {
return $aryData;
}
foreach ($headerRow as $colname) {
$aryData[$colname] = [];
}
while ($aryCsvData = fgetcsv($handle)){
foreach ($headerRow as $colname) {
$aryData[$colname][] = each($aryCsvData);
}
}
fclose($handle);
}
return $aryData;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.