我正在尝试获取具有用户将从“选择多个”html表单添加的所有属性的行(如prestashop产品属性,如果您已经看过它)。
让我们说: 我有一个像下面这样的数组列表 -
阵列( '姓名', 'id_attribute', 'id_category')
Example :
$array[] = array('name'=>'RED','id_attribute'=>1,'id_category'=>1) ;
RED 1 1
BLUE 2 1
XL 3 2
XXL 4 2
wool 5 3
cotton 6 3
现在我想生成列表中的所有可能组合,按其“id_category”/类别分组。喜欢 -
RED XXL WOOL
RED XL WOOL
BLUE XXL WOOL
BLUE XL WOOL
RED XXL COTTON
RED XL COTTON
等等。
我不知道该怎么做。我应该尝试嵌套的foreach或array_map吗?你有什么提示吗?
答案 0 :(得分:3)
你的问题形成不好,很难理解你真正想要的东西。但经过一遍又一遍的审视后,我认为这就是你要找的东西。 我已将评论和解释放在每一行之上。
//Your Array
$list_array = array(
array('RED','1','1'),
array('BLUE','2','1'),
array('XL','3','2'),
array('XXL','4','2'),
array('WOOL','5','3'),
array('COTTON','6','3')
);
//Arranging your array into a tree like structure, based on their categories
$category = array();
foreach ($list_array as $i=>$v)
{
if (!isset($category[$v[2]])) $category[$v[2]] = array();
array_push($category[$v[2]], $v[0]);
}
$category = array_values($category);
//Recursive function to mix and match the combinations
function combinations($arrays, $category=0)
{
if ($category == count($arrays) - 1) return $arrays[$category];
//get combination from next / latest categories
$childs = combinations($arrays, $category+1);
//merge each combination from childs to each element of this array
$return_array = array();
foreach ($arrays[$category] as $v)
{
foreach ($childs as $child)
{
//Put this combination to the return array
array_push($return_array, $v." ".$child);
}
}
return $return_array;
}
//This output array will contain all your lines
$output = combinations($category);
//Remove the following line, its only for testing purpose to show the lines
print_r($output);