PHP分层阵列 - 家长和孩子的 [英] PHP hierarchical array - Parents and childs

查看:146
本文介绍了PHP分层阵列 - 家长和孩子的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用PHP和MySQL与 Idiorm 。这可能是不相关的。

I use PHP and mySQL with Idiorm. That might not be relevant.

我的PHP数组


  • 这是父母和孩子的关系。

  • 0是根父。

  • 例:根父0有孩子33有孩子27具有
    孩子71。

<青霉>该阵列结构可以在需要解决该问题的改变。的

array (
  33 => 
    array (
      0 => '27',
      1 => '41',
  ),
  27 => 
    array (
      0 => '64',
      1 => '71',
  ),
  0 => 
    array (
      0 => '28',
      1 => '29',
      2 => '33',
  ),
)

我的分级结果

这样的事情,但是作为一个数组...

Something like this, but as an array...

  0 => 
      28
      29
      33
         27 =>
               64
               71
         41

资讯


  • 的深度是未知,它可以是无限的。我试过的foreach,但它可能不是这样。

我自己的想法


  • 某些递归函数?

  • 某些while循环?

我试过两个以上的,刚拿到一个烂摊子。这是一个显而易见的。

I tried both of the above, just got a mess. It's a brainer.

推荐答案

由@deceze的建议的工作。然而,输入数组需要改变豆蔻,像这样...

The suggestion by @deceze worked. However the input array needs to change a litte, like this...

$rows = array(
    array(
        'id' => 33,
        'parent_id' => 0,
    ),
    array(
        'id' => 34,
        'parent_id' => 0,
    ),
    array(
        'id' => 27,
        'parent_id' => 33,
    ),
    array(
        'id' => 17,
        'parent_id' => 27,
    ),
);

通过 http://stackoverflow.com/a/8587437/476

function buildTree(array $elements, $parentId = 0) {
    $branch = array();

    foreach ($elements as $element) {
        if ($element['parent_id'] == $parentId) {
            $children = buildTree($elements, $element['id']);
            if ($children) {
                $element['children'] = $children;
            }
            $branch[] = $element;
        }
    }

    return $branch;
}

$tree = buildTree($rows);

print_r( $tree );

这篇关于PHP分层阵列 - 家长和孩子的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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