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.
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.
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.
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.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With