把字串$str = '12,34,5';
拆分成數組$arr = [[1,3,5],[1,4,5],[2,3,5],[2 ,4,5]];
求把$str轉成$arr的php邏輯演算法;
世界只因有你2017-05-16 13:10:40
說明一下,使用 global 可能看起來不那麼優雅,但是這裡我就是寫一個示例方法,不就過於糾結啦,可自行優化
$str = '12,34,5';
$arr = explode(',', $str);
$step = $book = $result = [];
dfs(0);
print_r($result);
$str = '12,34';
$arr = explode(',', $str);
$step = $book = $result = [];
dfs(0);
print_r($result);
$str = '12,34,5,67';
$arr = explode(',', $str);
$step = $book = $result = [];
dfs(0);
print_r($result);
function dfs($s)
{
global $arr, $step, $result, $book;
if (!isset($arr[$s])) {
$result[] = array_values($step);
return;
}
for ($i = 0; $i < strlen($arr[$s]); $i++) {
if (!isset($book[$s][$i]) || $book[$s][$i] == 0) {
$book[$s][$i] = 1;
$step[$s] = $arr[$s][$i];
dfs($s + 1);
$book[$s][$i] = 0;
}
}
return;
}
PHP中文网2017-05-16 13:10:40
兩個陣列很好組合,2個嵌套的for迴圈即可,不確定個數的多數組就沒法這麼處理了,可以參考一些排序演算法的思路,多數組就透過遞歸其轉換為2個數組,如:[[1,2],[3,4],[5]],將其轉換為[[13,14,23,24],[5]],最後2個嵌套的for循環解決,參考代碼:
$str = '12,34,5';
$arr = [];
foreach (explode(',', $str) as $v) {
$arr[] = str_split($v);
}
print_r(fun($arr));
function fun($arr)
{
if (count($arr) >= 2) {
$tmparr = [];
$arr1 = array_shift($arr);
$arr2 = array_shift($arr);
foreach ($arr1 as $v1) {
foreach ($arr2 as $v2) {
$tmparr[] = $v1 . $v2;
}
}
array_unshift($arr, $tmparr);
$arr = fun($arr);
}
return $arr;
}