str_getcsv into a multidimensional array in php

后端 未结 3 1382
忘掉有多难
忘掉有多难 2021-01-31 18:47

I have csv values like this:

$csv_data = \"test,this,thing
             hi,there,this
             is,cool,dude
             have,fun\";

I want

3条回答
  •  情歌与酒
    2021-01-31 19:37

    Here is a very clean and simple solution:

    function parse_row($row) {
      return array_map('trim', explode(',', $row));
    }
    
    $rows   = str_getcsv($csv_data, "\n");
    $keys   = parse_row(array_shift($rows));
    $result = array();
    
    foreach ($rows as $row) {
      $row = parse_row($row);
      $row = array_pad($row, 3, NULL);
    
      $result[] = array_combine($keys, $row);
    }
    

提交回复
热议问题