3v4l.org

run code in 300+ PHP versions simultaneously
<?php $data = [ [ 'rates' => [1, 2], 'origin' => 1, ], [ 'rates' => [3, 4], 'origin' => 2, ], [ 'rates' => [5], 'origin' => 3, ], ]; $result = []; foreach ($data[0]['rates'] as $rate) { $tmp = [ 'rate' => $rate, 'origin' => $data[0]['origin'], ]; rates($tmp, [$data[1], $data[2]]); } function rates(array $baseRate, array $nextData): void { global $result; for ($i = 0; $i < count($nextData); ++$i) { foreach ($nextData[$i]['rates'] as $rate) { $tmp = []; $tmp[] = $baseRate; $tmp[] = [ 'rate' => $rate, 'origin' => $nextData[$i]['origin'], ]; for ($j = 0; $j < count($nextData); ++$j) { if ($i === $j) { continue; } foreach ($nextData[$j]['rates'] as $subRate) { $tmp[] = [ 'rate' => $subRate, 'origin' => $nextData[$j]['origin'], ]; } } $result[] = $tmp; } } } \print_r($result); $expected = [ [ [ 'rate' => 1, 'origin' => 1, ], [ 'rate' => 3, 'origin' => 2, ], [ 'rate' => 5, 'origin' => 3, ], ], [ [ 'rate' => 1, 'origin' => 1, ], [ 'rate' => 4, 'origin' => 2, ], [ 'rate' => 5, 'origin' => 3, ], ], [ [ 'rate' => 2, 'origin' => 1, ], [ 'rate' => 3, 'origin' => 2, ], [ 'rate' => 5, 'origin' => 3, ], ], [ [ 'rate' => 2, 'origin' => 1, ], [ 'rate' => 4, 'origin' => 2, ], [ 'rate' => 5, 'origin' => 3, ], ], ];
Output for 7.2.0 - 7.2.31, 7.3.0 - 7.3.19, 7.4.0 - 7.4.7, 8.0.0alpha1 - alpha2
Array ( [0] => Array ( [0] => Array ( [rate] => 1 [origin] => 1 ) [1] => Array ( [rate] => 3 [origin] => 2 ) [2] => Array ( [rate] => 5 [origin] => 3 ) ) [1] => Array ( [0] => Array ( [rate] => 1 [origin] => 1 ) [1] => Array ( [rate] => 4 [origin] => 2 ) [2] => Array ( [rate] => 5 [origin] => 3 ) ) [2] => Array ( [0] => Array ( [rate] => 1 [origin] => 1 ) [1] => Array ( [rate] => 5 [origin] => 3 ) [2] => Array ( [rate] => 3 [origin] => 2 ) [3] => Array ( [rate] => 4 [origin] => 2 ) ) [3] => Array ( [0] => Array ( [rate] => 2 [origin] => 1 ) [1] => Array ( [rate] => 3 [origin] => 2 ) [2] => Array ( [rate] => 5 [origin] => 3 ) ) [4] => Array ( [0] => Array ( [rate] => 2 [origin] => 1 ) [1] => Array ( [rate] => 4 [origin] => 2 ) [2] => Array ( [rate] => 5 [origin] => 3 ) ) [5] => Array ( [0] => Array ( [rate] => 2 [origin] => 1 ) [1] => Array ( [rate] => 5 [origin] => 3 ) [2] => Array ( [rate] => 3 [origin] => 2 ) [3] => Array ( [rate] => 4 [origin] => 2 ) ) )