火车头发布产品的时候,有颜色、尺码、性别等等产品属性,需要进行不重复的组合,变成不重复的数组
<?php function comb($a){ $a = array_filter($a); $out = array(); if (count($a) == 1) { $r = array_shift($a); foreach ($r as $v) $out[] = array($v); return $out; } foreach ($a as $k => $v){ $b = $a; unset($b[$k]); $r = comb($b); foreach ($v as $v1){ foreach ($r As $v2) $out[] = array_merge(array($v1), $v2); } break; } return $out; } $array1 = array(array('Red', 'Black', 'Yellow'),array('Boy','Girl'),array('S', 'M', 'L')); $result = comb($array1);
print_r($result);
?>
返回的结果如下:
Array ( [0] => Array ( [0] => Red [1] => Boy [2] => S ) [1] => Array ( [0] => Red [1] => Boy [2] => M ) [2] => Array ( [0] => Red [1] => Boy [2] => L ) [3] => Array ( [0] => Red [1] => Girl [2] => S ) [4] => Array ( [0] => Red [1] => Girl [2] => M ) [5] => Array ( [0] => Red [1] => Girl [2] => L ) [6] => Array ( [0] => Black [1] => Boy [2] => S ) [7] => Array ( [0] => Black [1] => Boy [2] => M ) [8] => Array ( [0] => Black [1] => Boy [2] => L ) [9] => Array ( [0] => Black [1] => Girl [2] => S ) [10] => Array ( [0] => Black [1] => Girl [2] => M ) [11] => Array ( [0] => Black [1] => Girl [2] => L ) [12] => Array ( [0] => Yellow [1] => Boy [2] => S ) [13] => Array ( [0] => Yellow [1] => Boy [2] => M ) [14] => Array ( [0] => Yellow [1] => Boy [2] => L ) [15] => Array ( [0] => Yellow [1] => Girl [2] => S ) [16] => Array ( [0] => Yellow [1] => Girl [2] => M ) [17] => Array ( [0] => Yellow [1] => Girl [2] => L ) )