Skip to content
Advertisement

Iterate array of arrays in reverse and subtract following subarray values from current subarray values

I have a dynamic multidimensional array like this:

$myarray = array(
            array(
                0 => 0,
                1 => 70, 
                2 => 19,
                3 => 0
            ),
            array(
                0 => 0,
                1 => 24,
                2 => 14
            ),
            array(
                0 => 0,
                1 => 15,
                2 => 11,
                3 => 0
            ),
            array(
                0 => 0,
                1 => 15,
                2 => 27,
                3 => 0
            )
        );

I need to loop through the subarrays and overwrite the current values of each subarray to represent the difference between the original value and the following value with respect to the subarray keys.

This describes the arithmetic desired on each subarray element (the value after the = is the new desired value):

$myarray = array(
            array(
                0 => 0 - 0 = 0
                1 => 70 - 24 = 46
                2 => 19 - 30 = -11
                3 => 0 - 0 = 0
            ),
            array(
                0 => 0 - 0 = 0
                1 => 24 - 0 = 24
                2 => 14 -(-16) = 30
                3 => 0 - 0 = 0
            ),
            array(
                0 => 0 - 0 = 0
                1 => 15 - 15 = 0
                2 => 11 - 27 = -16
                3 => 0 - 0 = 0
            ),
            array(
                0 => 0,
                1 => 15,
                2 => 27,
                3 => 0
            )
        );

I tried to do something, but it is not what I need and it contains errors:

$new_array = array();
foreach($myarray as $key => $values) {
    foreach($values as $k_key => $v_values) {
        $calc = $values[$k_key+1]-$v_values;
        array_push($new_array , $calc);
    }
}
var_dump($new_array);

Advertisement

Answer

  1. Start from 2nd last subarray, and loop toward the start
  2. Find the longer array’s length of the two targeted arrays
  3. Iterate and perform subtractions / declarations
  4. declare/overwrite new values as they are encountered

Code: (Demo)

$myarray = [
    [0, 70, 19, 0],
    [0, 24, 14],        // note missing 4th element
    [0, 15, 11, 0],
    [0, 15, 27, 0]
];

for ($i = count($myarray) - 2; $i >= 0; --$i) {
    $max = max(count($myarray[$i]), count($myarray[$i+1]));
    for($k = 0; $k < $max; ++$k) {
        $myarray[$i][$k] = ($myarray[$i][$k] ?? 0) - ($myarray[$i+1][$k] ?? 0);
    }
}

var_export($myarray);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement