Answer the question
In order to leave comments, you need to log in
How to make a combination of values from two arrays?
There is such an array:
$features = array(
3 => array(
1 => 1,
2 => 1,
3 => 1,
),
5 => array(
815 => 1,
816 => 1,
817 => 1,
),
);
3:1;5:815;
3:1;5:816;
3:1;5:817;
3:2;5:815;
3:2;5:816;
3:2;5:817;
3:3;5:815;
3:3;5:816;
3:3;5:817;
3:1;
3:2;
3:3;
Answer the question
In order to leave comments, you need to log in
// рекурсивно создать варианты для каждого корневого ключа
function create_variants($arr)
{
$items = [];
foreach ($arr as $key => $value) {
$vars = [$key];
if (!is_array($value)) {
$items[] = implode(';', $vars);
continue;
}
$variants = create_variants($value);
foreach ($variants as $variantValue) {
$items[] = implode(';', array_merge($vars, [$variantValue]));
}
}
return $items;
}
/**
* объединить варианты корневых ключей
* @param $partsCount количество объединяемых в одно вариантов
*/
function join_variants($items, $partsCount)
{
$result = [];
$joinable = array_chunk($items, ceil(count($items)/$partsCount));
foreach ($joinable as $chunk) {
foreach ($chunk as $index => $item) {
if (isset($result[$index])) {
$result[$index] .= ';'.$item;
} else {
$result[$index] = $item;
}
}
}
return array_map(function ($v) {
return $v.';';
}, $result);
}
var_dump(join_variants(
create_variants($features),
count($features)
));
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question