我有这样的csv值:
$csv_data = "test,this,thing
hi,there,this
is,cool,dude
have,fun";
Run Code Online (Sandbox Code Playgroud)
我想取一个完整的CSV字符串并将其读入一个多维数组,以便我得到:
array(
array(
'test' => 'hi',
'this' => 'there',
'thing' => 'this'
),
array(
'test' => 'is',
'this' => 'cool',
'thing' => 'dude'
),
array(
'test' => 'have',
'this' => 'fun',
'thing' => ''
)
);
Run Code Online (Sandbox Code Playgroud)
我想要这样的输出,请注意CSV值是动态的.
Wis*_*guy 35
假设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));
}
Run Code Online (Sandbox Code Playgroud)
如果行具有可变数量的列(如示例中,最后一行有2列而不是3列),请改用此循环:
foreach ($lines as $line) {
$row = array_pad(str_getcsv($line), count($head), '');
$array[] = array_combine($head, $row);
}
Run Code Online (Sandbox Code Playgroud)
这是一个完整的解决方案:
$lines = explode("\n", $csv_data);
$formatting = explode(",", $lines[0]);
unset($lines[0]);
$results = array();
foreach ( $lines as $line ) {
$parsedLine = str_getcsv( $line, ',' );
$result = array();
foreach ( $formatting as $index => $caption ) {
if(isset($parsedLine[$index])) {
$result[$formatting[$index]] = trim($parsedLine[$index]);
} else {
$result[$formatting[$index]] = '';
}
}
$results[] = $result;
}
Run Code Online (Sandbox Code Playgroud)
那么我们在这里做什么?
explode
explode
由于 CSV 中的第一行描述了数据格式,因此它必须与实际数据行 (和unset
)分开$results
)str_getcsv
归档时间: |
|
查看次数: |
17687 次 |
最近记录: |