我有这样的 csv 值:
$csv_data = "test,this,thing
hi,there,this
is,cool,dude
have,fun";
我想获取一个完整的 CSV 字符串并将其读入一个多维数组,以便得到:
array(
array(
'test' => 'hi',
'this' => 'there',
'thing' => 'this'
),
array(
'test' => 'is',
'this' => 'cool',
'thing' => 'dude'
),
array(
'test' => 'have',
'this' => 'fun',
'thing' => ''
)
);
我想要这样的输出,请注意 CSV 值是动态的。
最佳答案
假设 CSV 数据中的每一行都有相同的列数,这应该可行。
$lines = explode("\n", $csv_data);
$head = str_getcsv(array_shift($lines));
$array = array();
foreach ($lines as $line) {
$array[] = array_combine($head, str_getcsv($line));
}
如果行的列数可变(在您的示例中,最后一行有 2 列而不是 3 列),请改用此循环:
foreach ($lines as $line) {
$row = array_pad(str_getcsv($line), count($head), '');
$array[] = array_combine($head, $row);
}
关于php - str_getcsv 转换为 php 中的多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8353203/