str_getcsv成为php中的多维数组

Pin*_*wer 20 php csv

我有这样的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)

  • 那么在单个字段中包含 \n 的 csv 数据呢?csv 中的常用符号是用引号将这些字段括起来,例如“某个字段中的某个值”。因此,在解析时必须忽略那些 \n。你的爆炸方法会切断它们。 (3认同)

jsa*_*nen 7

这是一个完整的解决方案:

$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)

那么我们在这里做什么?

  • 首先,您的 CSV 数据被分成行数组explode
  • explode由于 CSV 中的第一行描述了数据格式,因此它必须与实际数据行 (和unset)分开
  • 为了存储结果,我们初始化一个新数组 ( $results)
  • Foreach 用于逐行迭代数据。对于每行:
    • 该行是用 PHP 解析的str_getcsv
    • 初始化一个空结果数组
    • 根据格式检查每一行。添加单元格并用空字符串填充缺失的列。