Search code examples
phparraysmultidimensional-arraysumgrouping

Group data from 2d array by column and count or sum other columns


I am build a multidimension array from data that has a multiple entries but some entries have the same value;

id      name      delivery#  weight    time
--------------------------------------------
12      test      112233     45        now
13      test      112234     456       now
14      testA     112245     33        later
15      testB     334421     334       later
...
...

and foreach id I push to array like so;

array_push($arraydata, array(
"id" => $id, 
"name" => $name,
"delivery" => $delivery,
"weight" => $weight,
"time" => $time
));

and later I use to loop through it;

foreach($arraydata as $arraydataItem) {

//do stuff...
//test appears twice - echo count & delivery values
//testA once - echo count
//testB once - echo count

}

Basically I want check how many times the same name value appears and add the weight values together for a total.

As then for each "delivery" with the same "name" divide the delivery weight by the total weight of "name" and get the percentage which I will use for calculating the percentage of the total cost of "name"..


Solution

  • Instead of creating that associative array using array_push(), you should create a multidimensional array like this,

    $arraydata[$name][] = array('id' => $id, 'delivery' => $delivery, 'weight' => $weight, 'time' => $time); 
    

    And as per your question,

    Basically I want check how many times the same name value appears and add the weight values together for a total.

    Simply use a foreach loop to loop through $arraydata array and display count and total weight associated for each name, like this:

    foreach($arraydata as $key => $arraydataItem){
        // Display count and total weight associated for each name
        echo $key . ": (count: " . count($arraydataItem) . ", total weight: " . array_sum(array_column($arraydataItem,'weight')) . ")<br />";
    }
    

    This will output:

    test: (count: 2, total weight: 501)
    testA: (count: 1, total weight: 33)
    testB: (count: 1, total weight: 334)
    

    Moreover, you can tweak this code to fulfil your further requirements.


    Note: If you want to see the structure of $arraydata array, do var_dump($arraydata);