Edward144
Edward144

Reputation: 493

PHP put values from CSV file into an array

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?

Upvotes: 2

Views: 1581

Answers (5)

Pankaj Makwana
Pankaj Makwana

Reputation: 3050

You can try below example for your question. Check first if array key exist or not. if key is not exist then assign 0 to that key then make sum of that key below the key exist condition.

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

while ($row = fgetcsv($file, 0, ',', '\\')) {
    if (!array_key_exists($row[0], $unique)) {
        $unique[$row[0]] = 0;
    }
    $unique[$row[0]] += $row[1];
}
echo "<pre>";
print_r($unique);

$unique[$row[0]] += $row[1]; this line will give you unique index with sum of unique index.

Here is the out of the above code.

Array
(
    [12345] => 35
    [67890] => 10
)

Upvotes: 0

mega6382
mega6382

Reputation: 9396

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];

Upvotes: 2

Alcinator
Alcinator

Reputation: 317

You're setting $unique[$row[0]] to true the line above.

Try this:

<?php
$data = [];
$file = fopen('test.csv', 'r');
while($row = fgetcsv($file, 0, ',', '\\')) {
  $value = isset($data[$row[0]]) ? $data[$row[0]] : 0;
  $value += $row[1];
  $data[$row[0]] = $value;
}
print_r($data);

This prints the following on my machine:

Array
(
  [12345] => 35
  [67890] => 10
)

Which you could then write to a CSV with something like

foreach($data as $k => $v) {
  echo "$k,$v\n"; // Replace this with a file write obviously
}

Upvotes: 0

Odyssey1111
Odyssey1111

Reputation: 134

The problem you have is that your key is numeric and the array wants to be numeric in stead of a alphanumeric key. If I face this kind of problem I like to sole it this way as a quick and dirty solution. Try this code in your loop.

$key = $row[0];
if (!array_key_exists("{$key}", $unique))
{
$unique["{$key}"] = $row[1];
}
else
{
$unique["{$key}"] += $row[1];
}

Upvotes: 0

CodeGhost
CodeGhost

Reputation: 319

$unique[$row[0]] is set to true in the line before. If I read this correctly, that means that if $row[0] is 12345, the $unique array will have the index 12345 filled with true.

I think you might want to use a Multidimensional array instead of a normal array?

Upvotes: 1

Related Questions