开发者

organize php array into multi level child parent organization

I found a snippet of code that took an array and organized it in parent child multi level organization. like the following

$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),
    );

it was able to add all the child arrays under their respectful parent. I can not find the code for that. anyone have an idea


<?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);


Note quite sure what structure you're trying to end up with, but maybe this'll get you started:

$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'];
}

Or do you want something like:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜