<?php
function traverse_combinations(...$arrays) {
$combinations = array();
$traverse = function ($index, $current, $arrays) use (&$traverse, &$combinations) {
if ($index == count($arrays)) {
$combinations[] = $current;
} else {
$array = $arrays[$index];
if (empty($array)) {
$traverse($index + 1, $current, $arrays);
} else {
foreach ($array as $element) {
$current[] = $element;
$traverse($index + 1, $current, $arrays);
array_pop($current);
}
}
}
};
$traverse(0, array(), $arrays);
return $combinations;
}
//测试数据
$options = array(
"Color" => array("Red", "Blue", "Green","White"),
"Size" => array("S", "M", "L","XL"),
);
$result = traverse_combinations(...array_values($options));
print_r($result);
//保持键名对应
$final_result = array();
foreach ($result as $combination) {
$current = array();
for ($i = 0; $i < count($combination); $i++) {
$key = ucfirst(array_keys($options)[$i]);
$current[$key] = $combination[$i];
}
$final_result[] = $current;
}
print_r($final_result);
PHP遍历所有数组组合,用于商品SKU组合生成
Previous Post
PHP中文分段不断句,将长字符串分割成不超过指定长度的方法 Next Post
ESP8266 小爱同学开机脚本硬接版
PHP中文分段不断句,将长字符串分割成不超过指定长度的方法 Next Post
ESP8266 小爱同学开机脚本硬接版
发表回复