递归函数来使用数组的foreach循环通过PHP父和子节点进行排序 [英] A recursive function to sort through parent and child nodes in PHP using a foreach loop on an array

查看:363
本文介绍了递归函数来使用数组的foreach循环通过PHP父和子节点进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我存储在数组中的数据集与亲子IDS本身的参考:
ID PARENT_ID 标题等顶级有一个 PARENT_ID 0 的,并且可以有无数的亲子关系。

I have a data set stored in an array that references itself with parent-child ids: id, parent_id, title etc. The top tier has a parent_id of 0, and there can be countless parent-child relationships.

所以我选在这个数组与递归函数内的的foreach 循环来核对它的父元素每个数组元素,我觉得我一直盯着在这种方法太长时间。

So I'm sorting through this array with a foreach loop within a recursive function to check each array element against its parent element, and I think I've been staring at this method too long.

我最终在正确的顺序的元素,但我似乎无法让我的列表中正确的嵌套,这让我觉得该方法没有真正发挥作用。

I do end up with the elements in the correct order, but I can't seem to get my lists nested correctly, which makes me think that the method doesn't really work.


  • 这是最好的途径走?

  • 我能做些什么来改善和解决这个问题的方法

  • 有另一种伎俩,我可以申请吗?

下面是我的源:

<div>
    <div>Subpages</div>

    <ul>
    <?php subPages($this->subpages->toArray(), 0) ?>
    </ul>
    <br>
    <a href="javascript:;" onclick="">Add New Subpage</a>
</div>

<?php
    function subPages($subpages, $parent){

        foreach($subpages as $key => &$page){

            $newParent =  $page['id'];

            //If the current page is the parrent start a new list
            if($page['id'] == $parent)
            {
                //Echo out a new list
                echo '<ul>';
                echo '<li class="collapsed">';
                echo '<a href="javascript:;" class="toggle">+</a>';
                echo '<a href="javascript:;" onclick="">'.$page['title'].'</a>';        

                subPages($subpages, $newParent);

                echo '</li>';
                echo '</ul>';
            }
            //If the page's parent id matches the parent provided
            else if($page['parent_id'] == $parent)
            {
                //Echo out the link
                echo '<li class="collapsed">';
                echo '<a href="javascript:;" class="toggle">+</a>';
                echo '<a href="javascript:;" onclick="">'.$page['title'].'</a>';

                //Set the page as the new parent
                $newParent = $page['id'];

                //Remove page from array
                unset($subpages[$key]);

                //Check the rest of the array for children
                subPages($subpages, $newParent);

                echo '</li>';
            }
        }
    }
?>

与往常一样,任何援助AP preciated。请让我知道,如果事情是不明确的。

As always, any assistance is appreciated. Please let me know if something isn't clear.

推荐答案

我怀疑你们仍然在寻找一个真正的答案,但它可能会帮助别人出的同样的问题。下面是一个递归函数诉诸数组将儿童的父母之下。

I doubt that you guys are still looking for a real answer to this, but it might help out others with the same problem. Below is a recursive function to resort an array placing children beneath parents.

$initial = array(
    array(
        'name' => 'People',
        'ID' => 2,
        'parent' => 0
        ),
    array(
        'name' => 'Paul',
        'ID' => 4,
        'parent' => 2
        ),
    array(
        'name' => 'Liz',
        'ID' => 5,
        'parent' => 2
        ),
    array(
        'name' => 'Comus',
        'ID' => 6,
        'parent' => 3
        ),
    array(
        'name' => 'Mai',
        'ID' => 7,
        'parent' => 2
        ),
    array(
        'name' => 'Titus',
        'ID' => 8,
        'parent' => 3
        ),
    array(
        'name' => 'Adult',
        'ID' => 9,
        'parent' => 6
        ),
    array(
        'name' => 'Puppy',
        'ID' => 10,
        'parent' => 8
        ),
    array(
        'name' => 'Programmers',
        'ID' => 11,
        'parent' => 4
        )   ,
    array(
        'name' => 'Animals',
        'ID' => 3,
        'parent' => 0
        )                           
    );


/*---------------------------------
function parentChildSort_r
$idField        = The item's ID identifier (required)
$parentField    = The item's parent identifier (required)
$els            = The array (required)
$parentID       = The parent ID for which to sort (internal)
$result     = The result set (internal)
$depth          = The depth (internal)
----------------------------------*/

function parentChildSort_r($idField, $parentField, $els, $parentID = 0, &$result = array(), &$depth = 0){
    foreach ($els as $key => $value):
        if ($value[$parentField] == $parentID){
            $value['depth'] = $depth;
            array_push($result, $value);
            unset($els[$key]);
            $oldParent = $parentID; 
            $parentID = $value[$idField];
            $depth++;
            parentChildSort_r($idField,$parentField, $els, $parentID, $result, $depth);
            $parentID = $oldParent;
            $depth--;
        }
    endforeach;
    return $result;
}

$result = parentChildSort_r('ID','parent',$initial);

print '<pre>';
print_r($result);
print '</pre>';

这是一个风下来的方法,消除从原来的数组元素,并将它们放到结果以适当的顺序设置。我把它给你多少有些通用的,所以它只是需要你告诉它你的ID字段与父字段叫什么。顶层项目都要求有一个PARENT_ID(但你的名字)的0。我还添加了一个深度标记,以每个项目,这样就可以在输出格式。

It's a wind down method that removes elements from the original array and places them into result set in the proper order. I made it somewhat generic for you, so it just needs you to tell it what your 'ID' field and 'parent' fields are called. Top level items are required to have a parent_id (however you name it) of 0. I also add a depth marker to each item so that you can format on output.

这篇关于递归函数来使用数组的foreach循环通过PHP父和子节点进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆