str_getcsv into a multidimensional array in php

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

    Assuming every row in the CSV data has the same number of columns, this should work.

    $lines = explode("\n", $csv_data);
    $head = str_getcsv(array_shift($lines));
    
    $array = array();
    foreach ($lines as $line) {
        $array[] = array_combine($head, str_getcsv($line));
    }
    

    If lines have a variable number of columns (as in your example, where the last line has 2 columns instead of 3), use this loop instead:

    foreach ($lines as $line) {
        $row = array_pad(str_getcsv($line), count($head), '');
        $array[] = array_combine($head, $row);
    }
    

提交回复
热议问题