<?php
$csv = array_map('str_getcsv', file('filename.csv'));
for ($j = 1; $j < count($csv); $j++) {
for ($i = 0; $i < count($csv[0]); $i++) {
$myArray[$csv[0][$i].$j] = $csv[$j][$i];
}
}
print_r($myArray);
Not the most elegant solution but will work for you. I used for loops so i can use their counters easier. The output result is :
Array
(
[firstName1] => test1
[lastName1] => Test1
[email1] => [email protected]
[firstName2] => test2
[lastName2] => Test2
[email2] => [email protected]
)
And my csv file looked like this:
firstName,lastName,email
test1,Test1,[email protected]
test2,Test2,[email protected]
The first loop starts the counter from position 1 so i avoid the headers, and will loop around the main csv array.
The nested loop will go through each of the nested arrays and based on the 1st one that holds the header info will concatenate the new key fields and create your new array.
If you want to have it exactly like in your example, with the brackets and the counter to start from 0 for the key field then you can simple:
<?php
$csv = array_map('str_getcsv', file('filename.csv'));
for ($j = 1; $j < count($csv); $j++) {
for ($i = 0; $i < count($csv[0]); $i++) {
$counter = $j-1;
$myArray[$csv[0][$i].'['.$counter.']'] = $csv[$j][$i];
}
}
print_r($myArray);
Which will output for you an array just like you requested in your question:
Array
(
[firstName[0]] => test1
[lastName[0]] => Test1
[email[0]] => [email protected]
[firstName[1]] => test2
[lastName[1]] => Test2
[email[1]] => [email protected]
)
str_getcsvand similar.$data['firstName[0]']. To get the data as$data['firstName'][0], then you'd need to have it as$data = array( 'firstName' => array( 0=>'test1'));.