I have a given array, built like this:
[[0,2,0,1], 0,5,0,0], 1,0,1,3]] (for the readability)
array(3) { [0]=> array(4) { [0] => int(0) [1] => int(2) [2] => int(0) [3] => int(1) } [1]=> array(4) { [0] => int(0) [1] => int(5) [2] => int(0) [3] => int(0) } [2]=> array(4) { [0] => int(1) [1] => int(0) [2] => int(1) [3] => int(3) } } This input can vary as you can imagine, in length and heights and numbers, but not in the semantic.
I'd like to "map" a simple function, which does some basic math, which should calculate as follows:
If there are 0's in the the columnn, ignore all further values (values before are still added). Otherwise add all values to a sum.
in my example above, I have to add:
2 + 5 + 1
- the 1st row has
0's in the first 2 lines, so we don't add the 1. - 2nd row has 2 + 5 (7), the
0afterwards doesn't matter - 3rd row same as 1st one
- 4th row only adds 1 (before the
0, the 3 afterwards is ignored).
I tried to iterate through the given matrix with nested foreach-statements like this:
foreach($matrix as $k => $v) { // $v = 0,1,1,2 ... foreach($v as $lineValues) { var_dump($lineValues); } } This gives me an output of:
int(0) int(1) int(1) int(2) int(0) int(5) int(0) int(0) int(2) int(0) int(3) int(3)
I thought about counting the elements in each row and divide this result afterwards to rebuild the array and to compare if there are 0's or not. If there is a 0, all further additions wouldn't be important, so I'd jump to the 2nd values with incrementing $j ...
$lineValues][$i][$j] // (1st row, 1st value) $lineValues][$i+1][$j] // (2nd row, 1st value) ... That didn't help me that much. I also tried to explode each line to build an easier-to-read array with explode("],", $v), but that didn't do the trick either.
Keeping all this in the back of my head, I thought about mapping a function to this, but this is where I'm stuck. I guess (correct me if I'm wrong), that such a function should be the wisest choice, when it comes down to performance?
,then iterate over it? You know that every 4th # is in the same column.