Answer the question
In order to leave comments, you need to log in
How to iterate over multiple arrays with the same values?
There are 3 arrays
$arr = [
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4],
];
$arr2 = [
[1, 2, 3, 4],
[1, 2, 3, 4],
];
$arr3 = [
[1, 2, 3, 4]
];
$result = [
[3, 6, 9, 12],
[2, 4, 6, 8],
[1, 2 ,3 , 4]
];
Answer the question
In order to leave comments, you need to log in
Option two.
1. learn about such a thing as a user-defined function . And put the summation code of one array into it. Then the loop will be inside the function, and there will be no need to write it three times. Call the function only three times
2. place these three arrays in another, that is, we will have one main array, the elements of which will be three (or 5) arrays with numbers. then it will be possible to iterate over this external array 1 time in the loop, and write a loop inside it for summing. once
Create a function where your logic is explicitly written:
function sumArrays(...$arrays) {
usort($arrays, fn($a, $b) => count($b) - count($a));
$biggest = $arrays[0];
$other = array_slice($arrays, 1);
$result = [];
foreach ($biggest as $rowIndex=>$row) {
$resultRow = [];
foreach ($row as $fieldIndex => $field) {
foreach ($other as $otherArray) {
if (array_key_exists($rowIndex, $otherArray)) {
$field += $otherArray[$rowIndex][$fieldIndex];
}
}
$resultRow[] = $field;
}
$result[] = $resultRow;
}
return $result;
}
var_dump(sumArrays($arr2, $arr3, $arr));
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question