I\'m new at PHP and keep struggling to read a CSV file into a 2D-array. I use the following file \'csv/team.csv\':
ID,Nickname,Shirtnumber,Position
1,Jimmy,0
I think str_getcsv comment contains very laconic solution, although it can be improved by using array_walk $userdata
parameter:
array_walk($teamdata, function(&$player, $_, $headers) {
$player = array_combine($headers, $player);
}, array_shift($teamdata));
Here is the demo.
list
just assigns array values to variables.You probably want to extract the headings first and combine that with each row to get an associative array:
$teamdata = file("csv/team.csv", FILE_IGNORE_NEW_LINES);
//get and remove first line to use as keys
$headings = str_getcsv(array_shift($teamdata));
foreach ($teamdata as $playerline) {
$player = str_getcsv($playerline);
//combine keys with values
$result[] = array_combine($headings, $player);
{
prev
on the array, however the array pointer is already at the first element so there is no previous and it returns false
. This is seen with: var_dump(prev($result));