1

我有一个数组如下。

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

如果有人可以解决它,将不胜感激。

4

1 回答 1

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'];
于 2013-06-23T18:14:11.817 回答