
数组:
$init = [ 'router/aaa' => [ 'opear' => ['1.php', '2.php'], 'list' => ['1.php', '2.php'] ], 'router/bbb' => [ 'url' => ['a.php', 'b.php'] ], 'router/homehelp' => [ 'opear' => [ 'update' => ['1.php', '2.php'], 'delete' => ['1.php', '2.php'] ], 'status' => ['start.php', 'stop.php'] ] ]; 效果:
array( 0 => 'router/aaa/opear/1.php', 1 => 'router/aaa/opear/2.php', 2 => 'router/aaa/list/1.php', 3 => 'router/aaa/list/2.php', 4 => 'router/bbb/url/a.php', 5 => 'router/bbb/url/b.php', 6 => 'router/home/help/opear/update/1.php', 7 => 'router/home/help/opear/update/2.php', ... ); 1 loginv2 2018-01-18 19:14:05 +08:00 via Android 递归遍历? |
2 loadinger 2018-01-18 19:28:41 +08:00 递归不就可以么。 |
5 eoo 2018-01-19 11:32:07 +08:00 via Android <?php //无限遍历数组 $a1 = array("a", "b", "c"); //一维数组 $a2 = array(array(21, 3, 6), array("a", "b", "c")); //二维数组 $a3 = array(array(array(5, 55), 4, 444), 2, 7, 6, 8, array("w", "d", array(3, 2, "a"), "s")); //多维不规则数组 function fun($a) { foreach ($a as $val) { if (is_array($val)) { //如果键值是数组,则进行函数递归调用 fun($val); } else { // 如果键值是数值,则进行输出 echo "$val<br />"; } //end if } //end foreach } //end fun //fun($a1); //fun($a2); fun($a3); ?> |
6 vincenttone 2018-01-19 11:56:40 +08:00 试试这个 ``` function r($arr, $pre = '') { $r = []; foreach ($arr as $_k => $_v) { if (is_array($_v) && !empty($_v)) { $r = array_merge($r, r($_v, $pre . '/' . $_k)); } else { $r[] = $pre . '/' . $_v; } return $r; } ``` |
7 vincenttone 2018-01-19 11:58:29 +08:00 顺路打听一下怎么发代码块呢? |
8 Bule OP |
9 Bule OP @vincenttone 好 6 啊,这方面的知识是多看看数据结构吗? |
10 dee 2018-01-19 14:16:16 +08:00 也贴一个 虽然不是迭代 ```php function router($ary, &$newAry, $pre = '') { foreach($ary as $key => $val) { if(is_array($val)) { router($val, $newAry, "$pre/$key"); } else { $newAry[] = "{$pre}/{$val}"; } } } ``` |
11 vincenttone 2018-01-19 14:25:35 +08:00 @Bule 我写的方法是一个递归,如果要和数据结构说到一起的话,写过一些树形结构的话,会有一些影响吧。 但是其实递归也算是一种常用的编程套路,很多时候比循环实现更容易一些吧,所以实践中经常会用到,多写代码也就好了。 |