日期:2014-05-17  浏览次数:20685 次

PHP的排列组合问题
现有数组$arr = array('Area','Income','Age','Gender');
想根据以上数组里的元素,组成新的数组如下:
Area Gender Income Age
Area Gender Age Income
Area Income Gender Age
Area Income Age Gender
Area Age Gender Income
Area Age Income Gender
Gender Income Age Area
Gender Income Area Age
Gender Age Area Income
Gender Age Income Area
Gender Area Age Income
Gender Area Income Age
Income Age Gender Area
Income Age Area Gender
Income Area Gender Age
Income Area Age Gender
Income Gender Area Age
Income Gender Age Area
Age Income Area Gender
Age Income Gender Area
Age Area Gender Income
Age Area Income Gender
Age Gender Area Income
Age Gender Income Area
希望各位大神能提供好的算法

------解决方案--------------------
$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;
}

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