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

前端 未结 2 1450
隐瞒了意图╮
隐瞒了意图╮ 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:06

    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.

    0 讨论(0)
  • 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));
    0 讨论(0)
提交回复
热议问题