Home > Back-end >  PHP CSV to associative array with top row as keys and following rows as values
PHP CSV to associative array with top row as keys and following rows as values

Time:11-23

I have just started learning PHP and stuck with the concept of Associative arrays. all of the examples i have seen so far are dealing with csv files. I actually have csv as a string where first row act as keys and all the following rows are values stored in multidimensional array.

the input csv string is like this or I believe this is how a csv string look like:

"fname,lname
 a,b
 c,d" 

the output should be: (consider the the input to be very long not just two lines)

[
   ["fname"=> "a" , "lname"=>"b"],
   ["fname"=> "c" , "lname"=>"d"]
]

as i am trying to learn PHP so this is what i have done so far:

 <?php

// original string
$OriginalString = "fname,lname,a,b,c,d,e,f";
//get each item
$SplittedString = array(explode(",",$OriginalString));
}    
?>

here is a close to solution for this question: PHP CSV to associative array with top row as keys and columns as value arrays

what I have thought to convert csv string to csv file and then use the normal solution already available online. That should do the job but i would like to see what other possible solution could be for this specific output.

CodePudding user response:

this is wrong:

// original string
$OriginalString = "fname,lname,a,b,c,d,e,f"

your original string had newlines which are very important here, meaning your $OriginalString should be:

// original string
// original string
$OriginalString = "fname,lname
a,b
c,d
e,f";

from there you can explode the string by lines,

$lines = explode("\n",$originalString);

from there it gets kindof-complex, you can iterate the lines with foreach, keeping in mind that the first line gives you the keys, and once you parse out the keys, you can iterate the next lines fragments with another explode foreach, like

$keys = array();
$parsed = array();
foreach($lines as $lineno => $line){
    if($lineno === 0){
        // the first line is special, it contains the keys
        $keys = explode(",",$line);
        continue;
    }
    $fragments = explode(",", $line);
    $current=array();
    foreach($fragments as $fragment_number => $value){
        $current[ $keys[$fragment_number] ]=$value;
    }
    $parsed [] = $current;
}

which gives

[
    {
        "fname": "a",
        "lname": "b"
    },
    {
        "fname": "c",
        "lname": "d"
    },
    {
        "fname": "e",
        "lname": "f"
    }
]

CodePudding user response:

Based on your string, I would

  1. Explode the string on a new line, giving an array of lines.
  2. Explode line 1 on a comma to get an array of keys
  3. Loop through the remains rows and explode on a comma to get an array of values

Now you can build your final array from your data.

  • Related