-1

I need to flatten a multidimensional array to form an associative array of unique values and their sums.

My sample array:

[
    [
        'winners' => [
            'Gold Member',
            'CROTCH SNIFFER',
            'TEAM #1'
        ],     
        'prizeTotal' => 20
    ],
    [
        'winners' => [
            'TEAM #1',
            'CROTCH SNIFFER'
        ],     
        'prizeTotal' => 60
    ],
    [
        'winners' => [
            'Gold Member',
            'TEAM #1'
        ],     
        'prizeTotal' => 30
    ],
    [
        'winners' => [
            'TEAM #1',
            'TEAM #2',
            'SCREW-NUT-BOLT'
        ],     
        'prizeTotal' => 90
    ]
]

Please forgive the names...it's not my DB.

In each data set, the prizeTotal is awarded to each value in the winners subarray.

How can I group the winners values and sum their respective prizeTotal values?

Desired result:

array (
  'Gold Member' => 50,
  'CROTCH SNIFFER' => 80,
  'TEAM #1' => 200,
  'TEAM #2' => 90,
  'SCREW-NUT-BOLT' => 90,
)
1
  • Post the code you have so far? Commented Jun 9, 2011 at 20:22

4 Answers 4

1

Assuming you can collect all your arrays into one i.e. :

$arrays = array($array1,$array2,....,$arrayn);

then

$grouping = array();

foreach($arrays AS $array)
{
   foreach($array['winners'] AS $k=>$v)
   {
      //check if the array key is a number, will contain a team, and if that
      //them is not alreay listed
      if(is_numeric($k) && !array_key_exists($v,$grouping))
         $grouping[$v] = 0;
      //sum the prize to the team's sum
      $grouping[$v] += intval($array['winners']['prizeTotal']);
   }
}
//the following is just for debugging
print_r($grouping);

this should produce something like:

$grouping[TEAM #1] = 200
$grouping[TEAM #2] = 90
$grouping[CROTCH SNIFFER] = 200
...
Sign up to request clarification or add additional context in comments.

Comments

0

You need to make a new array to hold your results, then for each of your existing arrays, check if you're already processed one for that team

If you have, then simply add the prizeTotal to the prizeTotal stored in your new array's entry for that team.

If not, simply add the team's entry to your new array.

Comments

0

To generate an associative array of unique teams and their cumulative scores:

  1. Use a loop to access each data subset
  2. Use extract() to conveniently access the winner and prizeTotal data as individual variables.
  3. Loop the winner elements
  4. Declare the winner as the key in the result array and the value should be the prizeTotal plus the cached value (or zero if there is no cached value).

Code: (Demo)

$result = [];
foreach ($array as $set) {
    extract($set);
    foreach ($winners as $winner) {
        $result[$winner] = ($result[$winner] ?? 0) + $prizeTotal;
    }
}
var_export($result);

Instead of calling extract(), "array destructuring" can create individual variables as well.

$result = [];
foreach ($array as ['winners' => $winners, 'prizeTotal' => $prizeTotal]) {
    foreach ($winners as $winner) {
        $result[$winner] = ($result[$winner] ?? 0) + $prizeTotal;
    }
}
var_export($result);

Comments

-1

I have made a function that imitates mysql SUM() and GROUP BY. I hope it will fit your needs:

           $in_a = array(
                array("a" => 0,"b"=>0,"s"=> 1),
                array("a" => 0,"b"=>0,"s"=> 2),
                array("a" => 1,"b"=>1,"s"=> 1),
                array("a" => 0,"b"=>1,"s"=> 1),
                array("a" => 0,"b"=>1,"s"=> 1),
                array("a" => 1,"b"=>0,"s"=> 1),         
                array("a" => 0,"b"=>1,"s"=> 1),         
                array("a" => 1,"b"=>1,"s"=> 1),         
                array("a" => 1,"b"=>0,"s"=> 1),         
            );//input array exaple
            $group_by_a = array("a","b");//input array will be grouped by these
            $sum_a = array("s"); //'s' values of input will be summed
            $out_a = array(); //this is the output array

            foreach($in_a as $in_i => $in)
            {
                $add = false;
                foreach($out_a as $out_i => $out)
                {
                    $add = true;
                    foreach($group_by_a as $group_by)
                        if($in[$group_by] != $out[$group_by])
                        {
                            $add = false; 
                            break;
                        }                   
                    if($add)
                    {
                        foreach($sum_a as $sum)
                            $out_a[$out_i][$sum] += $in[$sum];  
                        break;
                    }
                }
                if(!$add)
                {
                    foreach($group_by_a as $group_by)
                        $out_a[$in_i][$group_by] = $in[$group_by];
                    foreach($sum_a as $sum)
                        $out_a[$in_i][$sum] = $in[$sum];                    
                }                   
            }

the result:

Array
(
    [0] => Array
        (
            [a] => 0
            [b] => 0
            [s] => 3
        )

    [2] => Array
        (
            [a] => 1
            [b] => 1
            [s] => 2
        )

    [3] => Array
        (
            [a] => 0
            [b] => 1
            [s] => 3
        )

    [5] => Array
        (
            [a] => 1
            [b] => 0
            [s] => 2
        )

)

1 Comment

This answer is not tailored to the asked question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.