PHP字符串组合递归

<?php $arr = array(); $arr[] = array('1', '2', '3', '4', '5'); $arr[] = array('A', 'B', 'C', 'D'); $arr[] = array('a', 'b'); function digui($arr, $key) { if ( $key <= 0 ) { return $arr[0]; } $result = digui($arr, $key-1); $return = array(); foreach ($result as $value1) { foreach ($arr[$key] as $value2) { $return[] = $value1 . '-' . $value2; } } return $return; } $result = digui($arr, count($arr) - 1); print_r($result); exit(); 

OUTPUT:


Array
(
    [0] => 1-A-a
    [1] => 1-A-b
    [2] => 1-B-a
    [3] => 1-B-b
    [4] => 1-C-a
    [5] => 1-C-b
    [6] => 1-D-a
    [7] => 1-D-b
    [8] => 2-A-a
    [9] => 2-A-b
    [10] => 2-B-a
    [11] => 2-B-b
    [12] => 2-C-a
    [13] => 2-C-b
    [14] => 2-D-a
    [15] => 2-D-b
    [16] => 3-A-a
    [17] => 3-A-b
    [18] => 3-B-a
    [19] => 3-B-b
    [20] => 3-C-a
    [21] => 3-C-b
    [22] => 3-D-a
    [23] => 3-D-b
    [24] => 4-A-a
    [25] => 4-A-b
    [26] => 4-B-a
    [27] => 4-B-b
    [28] => 4-C-a
    [29] => 4-C-b
    [30] => 4-D-a
    [31] => 4-D-b
    [32] => 5-A-a
    [33] => 5-A-b
    [34] => 5-B-a
    [35] => 5-B-b
    [36] => 5-C-a
    [37] => 5-C-b
    [38] => 5-D-a
    [39] => 5-D-b
)

javascript 版本

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <script type="text/javascript"> arr = []; arr.push(['1', '2', '3', '4', '5']); arr.push(['A', 'B', 'C', 'D']); arr.push(['a', 'b']); function digui(arr, key) { if ( key <= 0 ) { return arr[0]; } var result = digui(arr, key-1); var ret = []; for ( var i in result ) { for ( var j in arr[key] ) { ret.push(result[i] + '-' + arr[key][j]); } } return ret; } result = digui(arr, arr.length - 1); for ( var i in result ) { document.getElementsByTagName('body')[0].innerHTML += result[i] + "<br />"; } </script>
</body>
</html>

你可能感兴趣的:(PHP字符串组合递归)