Home > Backend Development > PHP Tutorial > 三级归类不递归是怎样实现的呢 (附测试代码) 求解

三级归类不递归是怎样实现的呢 (附测试代码) 求解

WBOY
Release: 2016-06-13 12:55:00
Original
937 people have browsed it

三级分类不递归是怎样实现的呢 (附测试代码) 求解

本帖最后由 anydy2008 于 2013-01-06 12:07:44 编辑 看了几天前的一个帖子  
http://bbs.csdn.net/topics/390331161
当中有snmr_com 的热心回复,提到不递归实现分类的方法。

我就想,按照这个逻辑可否将类别实现树形数组结构呢。
下面是我用递归形式生成的  代码如下:
<br />
<?<br />
$arr = array(<br />
    <br />
    array('id'=>1,'city_name'=>'中国','rel_id'=>'1','pid'=>0),<br />
    array('id'=>2,'city_name'=>'广东','rel_id'=>'1-2','pid'=>1),<br />
    array('id'=>3,'city_name'=>'深圳','rel_id'=>'1-2-3','pid'=>2),<br />
    array('id'=>4,'city_name'=>'广州','rel_id'=>'1-2-4','pid'=>2)<br />
   <br />
);<br />
<br />
function find_subclass( $pid ){<br />
    <br />
    global $arr;<br />
    $__arr = array();<br />
    foreach ( $arr as $k=>$v )<br />
    {<br />
        <br />
        if( $v['pid']==$pid )$__arr[] = $v;<br />
        <br />
    }<br />
    return $__arr;<br />
    <br />
}<br />
<br />
function tree_subclass($pid=0){<br />
    <br />
    $__arr = array();<br />
    $__arr = find_subclass($pid);<br />
    if( !empty($__arr) ){<br />
        <br />
        foreach ( $__arr as $k=>$v )<br />
        {<br />
<br />
            $__arr[$k]['subclass'] = tree_subclass($v['id']);<br />
            <br />
        }<br />
        <br />
    }<br />
    return $__arr;<br />
}<br />
<br />
var_dump(tree_subclass(0));<br />
<br />
?><br />
<br />
Copy after login



期望通过不递归的形式得到的数组结构:

<br>
array(1) {<br>
  [0]=><br>
  array(5) {<br>
    ["id"]=><br>
    int(1)<br>
    ["city_name"]=><br>
    string(4) "中国"<br>
    ["rel_id"]=><br>
    string(1) "1"<br>
    ["pid"]=><br>
    int(0)<br>
    ["subclass"]=><br>
    array(1) {<br>
      [0]=><br>
      array(5) {<br>
        ["id"]=><br>
        int(2)<br>
        ["city_name"]=><br>
        string(4) "广东"<br>
        ["rel_id"]=><br>
        string(3) "1-2"<br>
        ["pid"]=><br>
        int(1)<br>
        ["subclass"]=><br>
        array(2) {<br>
          [0]=><br>
          array(5) {<br>
            ["id"]=> <div class="clear">
                 
              
              
        
            </div>
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template