PHP Reorder数组以反映父/ID层次结构 [英] PHP Reorder array to reflect parent / id hierarchy

查看:128
本文介绍了PHP Reorder数组以反映父/ID层次结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何重新排列以下数组

[0] => Array
    (
        [id] => 1
        [parent_id] => 0
        [name] => Accueil
    )

[1] => Array
    (
        [id] => 2
        [parent_id] => 0
        [name] => Exposants
    )

[2] => Array
    (
        [id] => 3
        [parent_id] => 0
        [name] => Visiteurs
    )

[3] => Array
    (
        [id] => 4
        [parent_id] => 0
        [name] => Medias
    )

[4] => Array
    (
        [id] => 5
        [parent_id] => 0
        [name] => Activités
    )

[5] => Array
    (
        [id] => 6
        [parent_id] => 1
        [name] => Contact
    )

[6] => Array
    (
        [id] => 7
        [parent_id] => 3
        [name] => Partenaires
    )

[7] => Array
    (
        [id] => 8
        [parent_id] => 2
        [name] => News
    )

因此,我想出了一个数组,该数组反映了id和parent_id字段所示的层次结构?数组键是ID字段,数组元素是父级.每次在此数组内部都有一个以其ID字段为键的子数组.样本:

So I come up with an array that reflects the hierarchy as shown by the id and parent_id fields? The array key is the ID field of array elements are parents. Inside this array is each time a child array that has its ID field as the key. Sample:

[1] => Array
        (
            [name] => Accueil
            [children] => array(
                [0] => bla,
                [3]     => bla2
            )
        )

    [2] => Array
        (
            [name] => Something
            [children] => array(
                [4] => bla3,
            )
        )

推荐答案

适用于任何深度,并允许孩子先于父母:

Works for any depth and allows children to precede parents:

<?php
$p = array(0 => array());
foreach($nodes as $n)
{
  $pid = $n['parent_id'];
  $id = $n['id'];

  if (!isset($p[$pid]))
    $p[$pid] = array('child' => array());

  if (isset($p[$id]))
    $child = &$p[$id]['child'];
  else
    $child = array();

  $p[$id] = $n;
  $p[$id]['child'] = &$child;
  unset($p[$id]['parent_id']);
  unset($child);

  $p[$pid]['child'][] = &$p[$id];    
}
$nodes = $p['0']['child'];
unset($p);
?>

$nodes结果上使用var_dump来查看结构.它接近您的建议.主要区别在于密钥不是id.

Use var_dump on the $nodes result to see the structure. It is close to what you suggested. The major difference is that the keys are not the ids.

这篇关于PHP Reorder数组以反映父/ID层次结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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