John Davidson

php - counting row values with different ids in multidimensional array

0 comments
Message:


I know there are a lot of topics about this, but just couldn't find any that would actually help me solve the problem.
Ok so i am having a problem with counting rows and values in multidimensional array (imported via .csv)



I am trying to achieve something like...


Array ( [0] => Array ( [0] => 1 [1] => 6278,31 [2] => 4) 
[1] => Array ( [0] => 2 [1] => 2,0 [2] => 2)
[2] => Array ( [0] => 3 [1] => 3,01 [2] => 3)
)

where [0] would be buyer id, 1 is total number of buys and [2] total cost.


My current code:


if(($s_open = fopen("sales.csv", "r")) !== FALSE) 
{
$s_count = count(file("sales.csv"));
while(($sales = fgetcsv($s_open, 100, ";")) !== FALSE)
{
...
}
fclose($s_open);
}

Thanks in advance.



My Answer:
> Array ( [id] => 1 [value] => 10 ) [1] => Array ( [id] => 1 [value] => 20 ) [2] => Array ( [id] => 2 [value] => 15 ) [3] => Array ( [id] => 2 [value] => 25 ) )_And i want to count the values for each id, so the output should be something like..._Array ( [1] => 30 [2] => 40 )__Here is a simple code snippet that should help you achieve this:_php

// Your multidimensional array
$array = array(
array('id' => 1, 'value' => 10),
array('id' => 1, 'value' => 20),
array('id' => 2, 'value' => 15),
array('id' => 2, 'value' => 25)
);

// Initialize an empty array to store the counts
$counts = array();

// Loop through the array and sum the values for each id
foreach ($array as $row) {
$id = $row['id'];
$value = $row['value'];

if (isset($counts[$id])) {
$counts[$id] += $value;
} else {
$counts[$id] = $value;
}
}

// Output the counts
print_r($counts);

?>


This code snippet should give you the desired output of counting the values for each id in the multidimensional array. Let me know if you need any further assistance!

Rate this post

5 of 5 based on 7233 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us