Prevent array overwriting and instead create new array index

前端 未结 2 714
星月不相逢
星月不相逢 2021-01-19 14:55

I have a file and I need the save the content of the file in my MySQL database. Here is the code that I am using to parse the file:

$lines = file($tmp_filenam         


        
相关标签:
2条回答
  • 2021-01-19 15:21

    The data in the array is being overwritten because you are reassigning the value of $key each time it is encountered.

    What you want to do is create a secondary array as the $key value and push nodes into that array this way you end up with your expected result.

    [
        'NM1' => ['...', '...'],
        'PR1' => ['...', '...']
    ]
    

    The code would be,

    while (($row = fgetcsv($handle, 1000, ";", "\"", "\n")) !== FALSE) {
        $key = array_shift($row);
        // Notice the extra []
        $data[$key][] = $row;
    }
    

    Each key will now contain an array with a node for each row encountered.

    0 讨论(0)
  • 2021-01-19 15:44

    try changing:

    ...
    $data[$key] = $row;
    

    to

    ...
    $data[][$key] = $row;
    
    0 讨论(0)
提交回复
热议问题