0

I have to join array array on same id, size and type and to sum num key value in php. I have found solutions only for one key, but I need match in 3 keys

Array
(
    [3] => Array
        (
            [id] => 460
            [size] => 24
            [num] => 1
            [price] => 6800.00
            [type] => 1
        )

    [2] => Array
        (
            [id] => 460
            [size] => 24
            [num] => 1
            [price] => 6800.00
            [type] => 1
        )

    [1] => Array
        (
            [id] => 460
            [size] => 24
            [num] => 1
            [price] => 6800.00
            [type] => 2
        )

)

I need to get array like this below, where everyting stays the same, and just num field is summed where id, type, and size key values are same

Array (

    [2] => Array
        (
            [id] => 460
            [size] => 24
            [num] => 2
            [price] => 6800.00
            [type] => 1
        )

    [1] => Array
        (
            [id] => 460
            [size] => 24
            [num] => 1
            [price] => 6800.00
            [type] => 2
        )

)
emir
  • 1,336
  • 1
  • 14
  • 33
  • possible duplicate of [Sum of columns in multidimensional array without loops](http://stackoverflow.com/questions/28875117/sum-of-columns-in-multidimensional-array-without-loops) - just change the callback function to check the three properties match – Tom Fenech Mar 05 '15 at 12:29
  • So what is the problem exactly? If you know how to do it for one, then you run it for a 3-tuple. – Artjom B. Mar 05 '15 at 12:34
  • this http://stackoverflow.com/questions/28875117/sum-of-columns-in-multidimensional-array-without-loops is not working for me, I dont know what values will be in array. I just need to sum num values if id, size and type have same value. I dont need just to sum values, I need to sum it if those three keys are same. I have found this to http://stackoverflow.com/questions/1496682/how-to-sum-values-of-the-array-of-the-same-key but it is not solution for my problem. I have searching for solution all morning. – emir Mar 05 '15 at 12:39
  • I have found solution here http://www.tagwith.com/question_251043_php-group-multidimensional-associative-array-and-sum-values-by-specific-key – emir Mar 05 '15 at 13:19

1 Answers1

0

I have solved very simply, using a temporary array like in this example

    $newArr = array();
foreach($your_arr as $key=>$val){
    $index = $val['context'].$val[1];
    if(isset($newArr[$index])){
        $val_0 = $newArr[$val['context'].$val[1]][0] + $val[0];
        $newArr[$val['context'].$val[1]] = array($val_0, $val[1], 'context'=>$val['context']);
    }else{
        $newArr[$val['context'].$val[1]] = $val;
    }
}
$result = array_values($newArr);
print '<pre>';
print_r($result);
print '</pre>';
emir
  • 1,336
  • 1
  • 14
  • 33