Coverting a csv-file to a PHP 2D-array

前端 未结 2 1452
隐瞒了意图╮
隐瞒了意图╮ 2021-01-18 19:20

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         


        
2条回答
  •  爱一瞬间的悲伤
    2021-01-18 20:18

    1. 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);
    { 
    
    1. You call 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));

提交回复
热议问题