0

I have import a csv file in my controller action. The structure of csv file is like given below.

Name , Phone , address
user1 , 99887766 , xyz 
user2, 99885566 , hjj 

Now I want array of arrays with csv header information as key and row data as value. The required output should be something like this.

[
"0" => [ "Name" => "user1" , "Phone" => "99887766" , "address" => "xyz" ],
"1" => [ "Name" => "user2" , "Phone" => "99885566" , "address" => "hjj" ],
]

I am able to get the row data with php explode. The problem is in setting the key as header given. Can anyone help-me for this.

2 Answers 2

4

Exploding might be dangerous - if there is a comma in any of the addresses, that row becomes invalid. I suggest using the native function str_getcsv() instead.

Here is an example of creating a general solution for csv to associative arrays. Below is a copy of the function.

function csv_to_array($filename='', $delimiter=',')
{
    if(!file_exists($filename) || !is_readable($filename))
        return FALSE;

    $header = NULL;
    $data = array();
    if (($handle = fopen($filename, 'r')) !== FALSE)
    {
        while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
        {
            if(!$header)
                $header = $row;
            else
                $data[] = array_combine($header, $row);
        }
        fclose($handle);
    }
    return $data;
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can try the following code

 $rows = file($csv_data_file);
 $header = array_shift($rows); //get the header out
 $header = explode(",", $header);
 $final_array = array();
 foreach ($rows as $row) {
      $row = explode(",", $row);
      $final_array[] = array($header[0] => $row[0], $header[1] => $row[1], $header[2] => $row[2]);
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.