douboshan1466 2017-10-23 13:18
浏览 145
已采纳

PHP将CSV文件中的值放入数组中

I have a CSV file with two columns. The first is an ID number and the second is the number of products with that ID. The CSV can have multiple copies of the same ID, and what I need to do is merge these and add the number of products for each ID together.

The CSV looks like this:

12345, 10
12345, 5
12345, 20
67890, 1
67890, 7
67890, 2

And I need it to turn into:

12345, 35
67890, 10

The way I have come up with to do this is to create a multidimentional array with an overall array containing the ID numbers, and each of those being an array containing the number of products. Then add up those values inside the arrays.

I am struggling to put the number of products into the ID arrays however. I am currently using this to create the array:

$unique = array();
$file = fopen('test.csv', 'r');

while($row = fgetcsv($file, 0, ',', '\\')) {
    $unique[$row[0]] = true;
    array_push($unique[$row[0]], $row[1]);
}

$row[0] is added to the array as a unique value, but when I try to push $row[1] into the ID array I get an error stating that the value is a boolean and not an array because for some reason $row[0] becomes a '1' instead of the ID when I try to use it in the array push.

What am I doing wrong?

  • 写回答

5条回答 默认 最新

  • dongyou7472 2017-10-23 13:29
    关注

    You can try the following:

    $unique = array();
    $file = fopen('test.csv', 'r');
    
    while($row = fgetcsv($file, 0, ',', '\\')) {
        $unique[$row[0]][] = $row[1];
    }
    var_dump($unique);
    

    This will provide the output like:

      12345 => 
        array (size=3)
          0 => string ' 10 ' (length=4)
          1 => string ' 5 ' (length=3)
          2 => string ' 20 ' (length=4)
      67890 => 
        array (size=3)
          0 => string ' 1 ' (length=3)
          1 => string ' 7 ' (length=3)
          2 => string ' 2' (length=2)
    

    Edit: if you also want the sum of $row[1] you can try the following inside the loop:

    $unique[$row[0]] = !isset($unique[$row[0]]) ? (int)$row[1] : $unique[$row[0]] + (int)$row[1];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?