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, ], ]; // нужно получить все возможные комбинации, как показано ниже $expected1 = [ [ [ '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, ], ], ]; $expected = []; $iteratorCount = 0; foreach ($data as $key => $block) { $data[$key]['iterator'] = 0; $iteratorCount++; } $tempCounter = 0; while ($tempCounter < $iteratorCount) { $temp = []; $tempCounter = 0; foreach ($data as $key => $block) { $temp[] = ['rate' => $block['rates'][$block['iterator']],'origin' => $block['origin']]; } $expected[] = $temp; foreach ($data as $key => $block) { if ($block['iterator'] + 1 < count($block['rates'])) { $data[$key]['iterator']++; break; } else { $data[$key]['iterator'] = 0; $tempCounter++; } } } print_r($expected);
based on P75JJ
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] => 2 [origin] => 1 ) [1] => Array ( [rate] => 3 [origin] => 2 ) [2] => Array ( [rate] => 5 [origin] => 3 ) ) [2] => Array ( [0] => Array ( [rate] => 1 [origin] => 1 ) [1] => Array ( [rate] => 4 [origin] => 2 ) [2] => Array ( [rate] => 5 [origin] => 3 ) ) [3] => Array ( [0] => Array ( [rate] => 2 [origin] => 1 ) [1] => Array ( [rate] => 4 [origin] => 2 ) [2] => Array ( [rate] => 5 [origin] => 3 ) ) )