PHP的排列组合问题
现有数组$arr = array('Area','Income','Age','Gender');
想根据以上数组里的元素,组成新的数组如下:
AreaGenderIncomeAge
AreaGenderAgeIncome
AreaIncomeGenderAge
AreaIncomeAgeGender
AreaAgeGenderIncome
AreaAgeIncomeGender
GenderIncomeAgeArea
GenderIncomeAreaAge
GenderAgeAreaIncome
GenderAgeIncomeArea
GenderAreaAgeIncome
GenderAreaIncomeAge
IncomeAgeGenderArea
IncomeAgeAreaGender
IncomeAreaGenderAge
IncomeAreaAgeGender
IncomeGenderAreaAge
IncomeGenderAgeArea
AgeIncomeAreaGender
AgeIncomeGenderArea
AgeAreaGenderIncome
AgeAreaIncomeGender
AgeGenderAreaIncome
AgeGenderIncomeArea
希望各位大神能提供好的算法
现有数组$arr = array('Area','Income','Age','Gender');
想根据以上数组里的元素,组成新的数组如下:
AreaGenderIncomeAge
AreaGenderAgeIncome
AreaIncomeGenderAge
AreaIncomeAgeGender
AreaAgeGenderIncome
AreaAgeIncomeGender
GenderIncomeAgeArea
GenderIncomeAreaAge
GenderAgeAreaIncome
GenderAgeIncomeArea
GenderAreaAgeIncome
GenderAreaIncomeAge
IncomeAgeGenderArea
IncomeAgeAreaGender
IncomeAreaGenderAge
IncomeAreaAgeGender
IncomeGenderAreaAge
IncomeGenderAgeArea
AgeIncomeAreaGender
AgeIncomeGenderArea
AgeAreaGenderIncome
AgeAreaIncomeGender
AgeGenderAreaIncome
AgeGenderIncomeArea
希望各位大神能提供好的算法
分享到:
------解决方案--------------------
Array
(
[0] => Area Income Age Gender
[1] => Area Income Gender Age
[2] => Area Age Gender Income
[3] => Area Age Income Gender
[4] => Area Gender Income Age
[5] => Area Gender Age Income
[6] => Income Age Gender Area
[7] => Income Age Area Gender
[8] => Income Gender Area Age
------解决方案--------------------
$arr = array('Area','Income','Age','Gender');
print_r(Arrangement($arr));
//排列 Arrangement
function Arrangement($arr = array(), $res = '') {
if(! is_array($arr) ) $arr = str_split($arr);
if(empty($arr)) $array[] = $res;
else foreach($arr AS $k => $v) {
unset($arr[$k]);
foreach( Arrangement($arr, $res . " $v") AS $t) $array[] = $t;
$arr[$k] = $v;
}
return $array;
}
登录后复制
(
[0] => Area Income Age Gender
[1] => Area Income Gender Age
[2] => Area Age Gender Income
[3] => Area Age Income Gender
[4] => Area Gender Income Age
[5] => Area Gender Age Income
[6] => Income Age Gender Area
[7] => Income Age Area Gender
[8] => Income Gender Area Age
08-31 12:50