Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

str_getcsv into a multidimensional array in php

Tags:

I have csv values like this:

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

I want to take an entire CSV string and read it into a multidemensional array so that I get:

array(    array(       'test' => 'hi',       'this' => 'there',       'thing' => 'this'    ),    array(       'test' => 'is',       'this' => 'cool',       'thing' => 'dude'    ),    array(       'test' => 'have',       'this' => 'fun',       'thing' => ''    ) ); 

I want an output like that, take note that the CSV value is dynamic.

like image 927
PinoyStackOverflower Avatar asked Dec 02 '11 07:12

PinoyStackOverflower


People also ask

How can I get multidimensional array in PHP?

Accessing multidimensional array elements: There are mainly two ways to access multidimensional array elements in PHP. Elements can be accessed using dimensions as array_name['first dimension']['second dimension']. Elements can be accessed using for loop. Elements can be accessed using for each loop.

Can we use foreach loop for multidimensional array in PHP?

You can simply use the foreach loop in combination with the for loop to access and retrieve all the keys, elements or values inside a multidimensional array in PHP.

What are multidimensional array in PHP explain with example?

A multidimensional array is an array containing one or more arrays. PHP supports multidimensional arrays that are two, three, four, five, or more levels deep. However, arrays more than three levels deep are hard to manage for most people.


1 Answers

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); } 
like image 98
Wiseguy Avatar answered Jan 13 '23 17:01

Wiseguy