0

First time posting here, I try to follow the questioning guides, sorry if I missed something.

I got a multidimensional array in PHP that do not have the same amount of results. Array[0] contains 6 while Array[1] only contains 4. here's an example:

Array
(
    [0] => Array
        (
            [0] => 122.7799987793
            [1] => 121.95999908447
            [2] => 121.90000152588
            [3] => 122.94000244141
            [4] => 122.18000030518
            [5] => 119.7200012207
        )

    [1] => Array
        (
            [0] => 37.705001831055
            [1] => 37.759998321533
            [2] => 37.889999389648
            [3] => 38.520000457764
        )

)

I managed to sum these 2 multidimentional arrays, using the following code:

$finalresult = array();

foreach($newarray[0] as $k => $v){
        $finalresult[$k] = array_sum(array_column($newarray, $k));  
}

So my result is:

Array
(
    [0] => Array
        (
            [0] => 160.4850006104
            [1] => 159.719997406
            [2] => 159,7900009155
            [3] => 161,4600028992
            [4] => 122.18000030518
            [5] => 119.7200012207
        )

)

So the SUM worked fine for the first 4 values, but then the last two are not matching the pattern.

What I am trying to achieve: In my database, I got an average number of each array. So basically what I would like the array_sum to do is:

array[0] + array[0]
array[1] + array[1]
array[2] + array[2]
array[3] + array[3]
array[4] + AVERAGE_VAR
array[5] + AVERAGE_VAR

To summarise: I am trying to achieve that the array with less values gets filled up with the average_variable_number which I pull from my MySQL database.

I tried a few things, but I can't wrap my head around it. I've been searching for a few days without any luck or tips where I have to look into.

Hope someone can show me an example of what the foreach function should look like to achieve the above.

Thank you a million in advance!!!

1 Answers1

1

If it's always just 2 arrays, you can loop up to the longer length, then test whether the element exists in both arrays, replacing a nonexistent element with the default value.

$len = max(count($newarray[0]), count($newarray[1]));
for ($i = 0; $i < len; $i++) {
    $val1 = array_key_exists($i, $newarray[0]) ? $newarray[0][$i] : $default;
    $val2 = array_key_exists($i, $newarray[1]) ? $newarray[1][$i] : $default;
    $finalresult[$i] = $val1 + $val2;
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • I can't cast a vote, because my reputation is not 15 points lol. But this did the trick @Barmar I did have to debug it, line 2 you mentioned: **$i < len;** Should be **$i < $len**, but amazing job! Thanks! – Maurice Gille Jan 15 '22 at 21:41