从数组创建层次结构

时间:2013-06-11 13:02:40

标签: arrays multidimensional-array hierarchy

我有一个数组如下。

array(
    0 => array(
        'parent' => 'Bigboss',
        'middle' => 'Technicians',
        'child' => 'Players'
    ),
    1 => array(
        'parent' => 'Company',
        'middle' => 'Manager',
        'child' => 'Employees'
    ),
    2 => array(
        'parent' => 'Bigboss',
        'middle' => 'Manager',
        'child' => 'Workers'
    ),
    3 => array(
        'parent' => 'Company',
        'middle' => 'Techinical Lead',
        'child' => 'Employees'
    ),
    4 => array(
        'parent' => 'Bigboss',
        'middle' => 'Workers',
        'child' => 'Employees'
    )
);

我希望这个数组的层次结构方式如

parent
=> middle
    => child
parent
=> middle
    => child

完全如下。

array(
    'Biggboss' => array(
        'Technicians' => array(
            0 => 'Players'
        ),
        'Manager' => array(
            0 => 'Workers'
        ),
        'Workers' => array(
            0 => 'Employees'
        )
    ),
    'Company' => array(
        'Manager' => array(
            0 => 'Employees'
        ),
        'Techinical Lead' => array(
            0 => 'Employees'
        )
    )
);

如果有人能解决它会更受欢迎。

1 个答案:

答案 0 :(得分:1)

我相信这有效......

$input = array(
    0 => array(
        'parent' => 'Bigboss',
        'middle' => 'Technicians',
        'child' => 'Players'
    ),
    1 => array(
        'parent' => 'Company',
        'middle' => 'Manager',
        'child' => 'Employees'
    ),
    2 => array(
        'parent' => 'Bigboss',
        'middle' => 'Manager',
        'child' => 'Workers'
    ),
    3 => array(
        'parent' => 'Company',
        'middle' => 'Techinical Lead',
        'child' => 'Employees'
    ),
    4 => array(
        'parent' => 'Bigboss',
        'middle' => 'Workers',
        'child' => 'Employees'
    )
);

$output = array();

foreach($input as $key => $value){
    if(!isset($output[$value['parent']])){ 
        $output[$value['parent']] = array();
    }
    $output[$value['parent']][$value['middle']] = array($value['child']);
}

print_r($output);

如果要在最后一个维度中允许多个值,请更改:

$output[$value['parent']][$value['middle']] = array($value['child']);

$output[$value['parent']][$value['middle']][] = $value['child'];