>  기사  >  백엔드 개발  >  PHP的排列组合问题

PHP的排列组合问题

WBOY
WBOY원래의
2016-06-23 14:15:12777검색

现有数组$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));//排列 Arrangementfunction 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
    [9] =>  Income Gender Age Area
    [10] =>  Income Area Age Gender
    [11] =>  Income Area Gender Age
    [12] =>  Age Gender Area Income
    [13] =>  Age Gender Income Area
    [14] =>  Age Area Income Gender
    [15] =>  Age Area Gender Income
    [16] =>  Age Income Gender Area
    [17] =>  Age Income Area Gender
    [18] =>  Gender Area Income Age
    [19] =>  Gender Area Age Income
    [20] =>  Gender Income Age Area
    [21] =>  Gender Income Area Age
    [22] =>  Gender Age Area Income
    [23] =>  Gender Age Income Area
)

<?php$arr = array('Area','Income','Age','Gender');print_r(Arrangement($arr));function Arrangement($arr, $k=null) {	if($k !== null) {		unset($arr[$k]);	}	if(count($arr) == 1) {		return $arr;	}	$result = array();	foreach($arr as $k => $v) {		foreach(Arrangement($arr, $k) as $av) {			$result[] = $v . ' ' . $av;		}	}	return $result;}

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.