0

This Question might seem duplicate, but I swear to have tried and tried thousands of solutions for many hours now...

I have got an associative multidimentional array like this:

    1 => 
    array (size=1)
      'Pld' => 
        array (size=2)
          'score_good_answers' => string '1' (length=1)
          'score_bad_answers' => string '0' (length=1)
  2 => 
    array (size=1)
      'Aln' => 
        array (size=2)
          'score_good_answers' => string '0' (length=1)
          'score_bad_answers' => string '1' (length=1)
  3=> 
    array (size=1)
      'IPS' => 
        array (size=2)
          'score_good_answers' => string '1' (length=1)
          'score_bad_answers' => string '0' (length=1)
 4 => 
    array (size=1)
      'Pld' => 
        array (size=2)
          'score_good_answers' => string '1' (length=1)
          'score_bad_answers' => string '0' (length=1)
  5 => 
    array (size=1)
      'Aln' => 
        array (size=2)
          'score_good_answers' => string '1' (length=1)
          'score_bad_answers' => string '0' (length=1)
 6 => 
        array (size=1)
          'Aln' => 
            array (size=2)
              'score_good_answers' => string '1' (length=1)
              'score_bad_answers' => string '0' (length=1)

FOR Var_Export:

1=> array ( 'Pld' => array ( 'score_good_answers' => '1', 'score_bad_answers' => '0', ), ), 2 => array ( 'Aln' => array ( 'score_good_answers' => '0', 'score_bad_answers' => '1', ), ), 3 => array ( 'IPS' => array ( 'score_good_answers' => '1', 'score_bad_answers' => '0', ), ), 4 => array ( 'Pld' => array ( 'score_good_answers' => '1', 'score_bad_answers' => '0', ), ),  5 => array ( 'Aln' => array ( 'score_good_answers' => '1', 'score_bad_answers' => '0', ), ),  6 => array ( 'Aln' => array ( 'score_good_answers' => '1', 'score_bad_answers' => '0', ), ),

I need to SUM the all the 'score_good_answers' and the 'score_bad_answers' for all Alns and Plds and so forth.

The Worse case scenario is that, this keys i.e: are changeable values.

At this level, whatever solution that works will be well appreciated.

I tried the Accepted Answer in this SO Question: How to sum values of the array of the same key?

However, It seems to throw several Errors....

And I Tried Several More Solutions from several SO Questions, i.e: How to sum values of the array of the same key?, Array sum of value based on same key, How to sum values via the same key and group by other key and many more...

An other close one was this:How to sum same array in php

And tried:

$array2 = array();
    for($f = 0; $f<count($getCategories); $f++){

        foreach($getCategories[$i] as $k=>$v) {
    if(!isset($array2[$v['Aln']])) {
        $array2[$v['Aln']] = $v;
    } else {
        $array2[$v['Aln']]['score_good_answers'] += $v['score_good_answers'];
    }
}

        }   var_dump($array2);

I still get Several Errors including invalid arguments undefined offsets and many more

Humbly request for any suggestion.

Thank you very much

Community
  • 1
  • 1
Universal Grasp
  • 1,835
  • 3
  • 20
  • 29
  • 1
    Well the first thing you can do to help yourself is choose better variable names; think about what $f, $I, $v, etc, actually *mean*, and see how your code reads when you substitute them in. Create some intermediate variables as well, to break up hard-to-read expressions like `$array2[$v['Aln']]['score_good_answers']` into multiple steps, with a name for what each value along the way represents. – IMSoP Nov 26 '14 at 20:24
  • @IMSoP, Sorry for the mess, I got those `var` names from the SO Question that I was trying to use... Thanx for noting that – Universal Grasp Nov 26 '14 at 20:28
  • Please use var_export instead of var_dump when pasting to SO, it uses a format that can be copy-pasted directly to php... – rjdown Nov 26 '14 at 20:33
  • 1
    @rjdown: Please See Update for `var_export`. Thank you – Universal Grasp Nov 26 '14 at 20:42

3 Answers3

1

You can use this code:

$answers = array();

foreach ($getCategories as $categories){

    foreach($categories as $category => $scores){

        foreach ($scores as $type => $score){

            if (isset($answers[$category][$type])){
                $answers[$category][$type] += (int) $score;
            } else {
                $answers[$category][$type] = (int) $score;
            }

        }

    }

}

The output of will be the following array:

Array
(
    [Pld] => Array
        (
            [score_good_answers] => 2
            [score_bad_answers] => 0
        )

    [Aln] => Array
        (
            [score_good_answers] => 2
            [score_bad_answers] => 1
        )

    [IPS] => Array
        (
            [score_good_answers] => 1
            [score_bad_answers] => 0
        )

)
vicente
  • 2,613
  • 4
  • 22
  • 27
  • While it's great that this helped in this case, this answer lacks any explanation of what was changed, and how the OP and other readers can avoid similar problems in the future. – IMSoP Nov 26 '14 at 21:46
0

The variable that holds the key is named $f, but you try to use the undefined variable $i on the next line, see? That is one of your warnings and will not do what you want it to. Use $f on the second line.

for($f = 0; $f<count($getCategories); $f++){
    foreach($getCategories[$i] as $k=>$v) {

Your data structure seems a bit odd? Is there always just one key in the second top-most array?

This would be prettier if possible:

array(2) {
  [0] => stdClass#1 (3) {
    public $name => string(4) "Pld"
    public $score_good_answers => int(1)
    public $score_bad_answers=> int(0)
  }
  [1] => stdClass#1 (3) {
    public $name => string(4) "Aln"
    public $score_good_answers => int(0)
    public $score_bad_answers=> int(1)
  }
}

I can not see what end result you want, but give this a try, might not fit what you want though.

$goodAnswersByCategoryDataKey = array();
$badAnswersByCategoryDataKey = array();

foreach ($categories as $i => $category) {
    foreach ($category as $categoryDataKey => $categoryData) {
        if (!isset($goodAnswersByCategoryDataKey[$categoryDataKey])) {
            $goodAnswersByCategoryDataKey[$categoryDataKey] = 0;
        }
        $goodAnswersByCategoryDataKey[categoryDataKey] += $categoryData['score_good_answers'];

        if (!isset($badAnswersByCategoryDataKey[$categoryDataKey])) {
            $badAnswersByCategoryDataKey[$categoryDataKey] = 0;
        }
        $badAnswersByCategoryDataKey[$categoryDataKey] += $categoryData['score_bad_answers'];
    }
}

var_dump(goodAnswersByCategoryDataKey);
var_dump(badAnswersByCategoryDataKey);
oldwizard
  • 5,012
  • 2
  • 31
  • 32
0

If it's an iterative structure like in your example you can do this :

$answers = [];
$nbCat = count($getCategories);
for($i = 0; $i < $nbCat; $i++) {
    foreach($getCategories[$i] as $key => $scores) {
        if(empty($answers[$key])) {
             $answers[$key] = $scores;
        }
        else {
            $answers[$key]['score_good_answers'] += $scores['score_good_answers'];
            $answers[$key]['score_bad_answers'] += $scores['score_bad_answers'];
        }
    }
}
Kulvar
  • 1,139
  • 9
  • 22