将php数组组织成多级子父组织

时间:2011-07-21 19:19:15

标签: php arrays multidimensional-array

我找到了一个代码片段,它采用了一个数组并将其组织在父子多级组织中。如下

$phases = array(
    array('id'=>1,'name'=>'First Step','parent_id'=>0,'percentage'=>.50,'order'=>1),
    array('id'=>2,'name'=>'Second Step','parent_id'=>0, 'percentage'=>.50,'order'=>2),
    array('id'=>3,'name'=>'Third Step','parent_id'=>2, 'percentage'=>.25,'order'=>3),
    array('id'=>4,'name'=>'Fourth Step','parent_id'=>2, 'percentage'=>.25,'order'=>1),
    array('id'=>5,'name'=>'Fifth Step','parent_id'=>2, 'percentage'=>.25,'order'=>1),
    array('id'=>6,'name'=>'Sixth Step','parent_id'=>2, 'percentage'=>.25,'order'=>1),
    );

它能够在尊敬的父母下添加所有子数组。我找不到那个代码。任何人都有一个想法

2 个答案:

答案 0 :(得分:2)

<?php
$phases = array(
    array('id'=>1,'name'=>'First Step','parent_id'=>0,'percentage'=>.50,'order'=>1),
    array('id'=>2,'name'=>'Second Step','parent_id'=>0, 'percentage'=>.50,'order'=>2),
    array('id'=>3,'name'=>'Third Step','parent_id'=>2, 'percentage'=>.25,'order'=>3),
    array('id'=>4,'name'=>'Fourth Step','parent_id'=>2, 'percentage'=>.25,'order'=>1),
    array('id'=>5,'name'=>'Fifth Step','parent_id'=>2, 'percentage'=>.25,'order'=>1),
    array('id'=>6,'name'=>'Sixth Step','parent_id'=>2, 'percentage'=>.25,'order'=>1),
    //just to add levels
    array('id'=>7,'name'=>'7th Step','parent_id'=>5, 'percentage'=>.25,'order'=>1),
    array('id'=>8,'name'=>'8th Step','parent_id'=>6, 'percentage'=>.25,'order'=>1)
    );

$treearr = array('0' => array('children'=> array()));
foreach($phases as $phase){
    if(!isset($treearr[$phase['id']]['children'])) $phase['children'] = $treearr[$phase['id']]['children'];
    $treearr[$phase['id']] = $phase;
    if(!isset($treearr[$phase['parent_id']])) $treearr[$phase['parent_id']] = array('children'=> array());
    $treearr[$phase['parent_id']]['children'][] = &$treearr[$phase['id']];
}
$tree = $treearr[0];
unset($treearr);
var_dump($tree);

答案 1 :(得分:0)

请注意你确定要结束的结构,但也许这会让你开始:

$multidim = array();
$multidim[0] = array();

foreach ($phases as $phase) {
    $multidim[$phase['id']] = array(
        'name' => $phase['name'],
        'children' => array(),
        'percentage' => $phase['percentage'],
        'parent_id' => $phase['parent_id']
    );
    $multidim[$phase['parent_id']]['children'][] = $phase['id'];
}

或者你想要这样的东西:

$phases[0][2][3] = array('name' => 'Third Step', 'percentage' => 0.25, 'order' => 3);