Search code examples
phparraysmultidimensional-arraytransposedivision

Synchronously iterate a flat array and 2d array, transpose the rows, then perform division


I need to loop over a 2d array, access its columnar data and perform division against the corresponding value in a flat array.

The flat array:

$array1 = [
    'maxwater' => 1,
    'maxfodder' => 2,
    'maxmob' => 3,
    'maxalt' => 4,
    'maxhum' => 5,
    'mintemp' => 6
];

The 2d array:

$array2 = [
    [2, 3, 4, 4, 1, 2],
    [3, 2, 1, 4, 1, 3],
    [4, 1, 2, 3, 1, 3],
    [3, 4, 2, 1, 1, 3],
    [1, 2, 2, 2, 3, 3]
];

What I want to do here is only to divide each column in $array2 by the respective number in $array1.

For example,

  • the first value in $array1 (maxwater) has a value of 1. This number should be used to divide each value in the first column of $array2 (2, 3, 4, 3, 1).
  • Then the next value in $array2 (maxfodder) is 2. The second column values in $array2 (3, 2, 1, 4, 2) should be divided by 2.
  • This process should be repeated for all of the columns in $array2.

And I already try using this code, but it generates an error:

Notice: Undefined offset: 0 in C:\xampp\htdocs\Livestockmapping\dsssawprocess.php on line 42
Warning: Division by zero in C:\xampp\htdocs\Livestockmapping\dsssawprocess.php on line 42 0

Code:

$yaxis = sizeof($array2);
$xaxis = max(array_map('count', $array2));

echo $xaxis;
echo $yaxis;

//normalization
for($i=0; $i < $xaxis; $i++)
{
    for($j=0; $j < $yaxis; $j++)
    {
        $c1norm = round($array2[$i][$j]/$array1[$j]);
        echo $c1norm;
    }
}

Can someone help me to find the correct way to do this?

edit: My second coding attempt:

foreach($array1 as $v){
    echo (array_sum(array_column($array2, $v - 1)) / $v) . "<br />";
}

It provides a result like this:

Array
(
    [0] => 13
    [1] => 6
    [2] => 3.6666666666667
    [3] => 3.5
    [4] => 1.4
    [5] => 2.3333333333333
)

But what I want is to divide every column value in $array2 like this:

2 / 1 = 2
3 / 1 = 3
4 / 1 = 4
3 / 1 = 3
1 / 1 = 1

3 / 2 = 2
2 / 2 = 1
1 / 2 = 1
4 / 2 = 2
2 / 2 = 1

4 / 3 = 1
1 / 3 = 0
2 / 3 = 1
2 / 3 = 1
2 / 3 = 1

...and so on.


Solution

  • Right now, you're dividing the elements based of the matrix of $array2.

    Include the for loop of the $array1 (each of it) and apply it on each column of $array2

    $array2[$j][$i] 
            ^ column first
    

    Example:

    // $array1 = array_values($array1); numeric index conversion
    $c = count($array1);
    $xaxis = sizeof($array2);
    $yaxis = max(array_map('count', $array2));
    
    // normalization
    for($i = 0; $i < $c; $i++) {
        for($j = 0; $j < ($yaxis - 1); $j++) {
            $c1norm = round($array2[$j][$i] / $array1[$i]);
            echo $c1norm;
        }
    }
    

    Demo