<?php
function mergeResult($a, $b, $needJoin = true) {
// fixme: увы не хватает времени на допилку...
return mergeResult($a, $r, false);
}, $b);
}
function buildLevel
(array $words, $level) { // с первым уровнем все просто
if ($level === 1) return [implode(' ', $words)];
// со вторым чуть по сложнее...
$result = [];
$chunk = [];
while(count($words) >= $level) { // отделяем первое слово из "строки" и зановим его к первому "слагаемому"
$result[] = mergeResult(buildLevel($chunk, 1), buildLevel($words, $level-1), $level > 2);
}
return $result;
}
// я торопился по сему вот так...
PD9waHAKZnVuY3Rpb24gbWVyZ2VSZXN1bHQoJGEsICRiLCAkbmVlZEpvaW4gPSB0cnVlKSB7CgkvLyBmaXhtZTog0YPQstGLINC90LUg0YXQstCw0YLQsNC10YIg0LLRgNC10LzQtdC90Lgg0L3QsCDQtNC+0L/QuNC70LrRgy4uLgogICAgaWYgKCEkbmVlZEpvaW4pIHJldHVybiBhcnJheV9tZXJnZSgkYSwgJGIpOwogICAgcmV0dXJuIGFycmF5X21hcChmdW5jdGlvbiAoJHIpIHVzZSAoJGEpIHsKICAgICAgICByZXR1cm4gbWVyZ2VSZXN1bHQoJGEsICRyLCBmYWxzZSk7CiAgICB9LCAkYik7Cn0KCmZ1bmN0aW9uIGJ1aWxkTGV2ZWwoYXJyYXkgJHdvcmRzLCAkbGV2ZWwpIHsKICAgIC8vINGBINC/0LXRgNCy0YvQvCDRg9GA0L7QstC90LXQvCDQstGB0LUg0L/RgNC+0YHRgtC+CiAgICBpZiAoJGxldmVsID09PSAxKSByZXR1cm4gW2ltcGxvZGUoJyAnLCAkd29yZHMpXTsKCiAgICAvLyDRgdC+INCy0YLQvtGA0YvQvCDRh9GD0YLRjCDQv9C+INGB0LvQvtC20L3QtdC1Li4uCiAgICAkcmVzdWx0ID0gW107CiAgICAkY2h1bmsgPSBbXTsKICAgIHdoaWxlKGNvdW50KCR3b3JkcykgPj0gJGxldmVsKSB7CiAgICAgICAgLy8g0L7RgtC00LXQu9GP0LXQvCDQv9C10YDQstC+0LUg0YHQu9C+0LLQviDQuNC3ICLRgdGC0YDQvtC60LgiINC4INC30LDQvdC+0LLQuNC8INC10LPQviDQuiDQv9C10YDQstC+0LzRgyAi0YHQu9Cw0LPQsNC10LzQvtC80YMiCiAgICAgICAgYXJyYXlfcHVzaCgkY2h1bmssIGFycmF5X3NoaWZ0KCR3b3JkcykpOwogICAgICAgICRyZXN1bHRbXSA9IG1lcmdlUmVzdWx0KGJ1aWxkTGV2ZWwoJGNodW5rLCAxKSwgYnVpbGRMZXZlbCgkd29yZHMsICRsZXZlbC0xKSwgJGxldmVsID4gMik7CiAgICB9CglyZXR1cm4gJHJlc3VsdDsKfQoKJHdvcmRzID0gZXhwbG9kZSgnICcsICdhIGIgYyBkJyk7Ci8vINGPINGC0L7RgNC+0L/QuNC70YHRjyDQv9C+INGB0LXQvNGDINCy0L7RgiDRgtCw0LouLi4KdmFyX2V4cG9ydChidWlsZExldmVsKCR3b3JkcywgMykpOwp2YXJfZXhwb3J0KGJ1aWxkTGV2ZWwoJHdvcmRzLCA0KSk7
array (
0 =>
array (
0 =>
array (
0 => 'a',
1 => 'b',
2 => 'c d',
),
1 =>
array (
0 => 'a',
1 => 'b c',
2 => 'd',
),
),
1 =>
array (
0 =>
array (
0 => 'a b',
1 => 'c',
2 => 'd',
),
),
)array (
0 =>
array (
0 =>
array (
0 => 'a',
1 =>
array (
0 => 'b',
1 => 'c',
2 => 'd',
),
),
),
)