S
S
snake22022-03-15 15:45:55
PHP
snake2, 2022-03-15 15:45:55

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]
];


Is it possible to add them without using a cycle for each array, since there can be 4 and 5 arrays, and for each to write a cycle is such an occupation?
Can somehow change the structure of the returned data?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
FanatPHP, 2022-03-15
@FanatPHP

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

I
Immortal_pony, 2022-03-15
@Immortal_pony

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;
}

... Then use it on any number of arrays
var_dump(sumArrays($arr2, $arr3, $arr));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question