str_getcsv into a multidimensional array in php

后端 未结 3 1389
忘掉有多难
忘掉有多难 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:26

    Here is a complete solution:

    $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;
    }
    

    So what are we doing here?

    • First, your CSV data is split into array of lines with explode
    • Since the first row in your CSV describes data format, it must be separated from the actual data rows (explode and unset)
    • For storing the results, we initialize a new array ($results)
    • Foreach is used to iterate through the data line by line. For each line:
      • Line is parsed with PHP's str_getcsv
      • An empty result array is initialized
      • Each line is inspected in the light of the format. Cells are added and missing columns are padded with empty strings.

提交回复
热议问题