Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I've an array as follows.

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

I want this array in heirarchy way like

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

Exactly like as follows.

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

if anyone could solve it would be more appreciated.

share|improve this question
    
@hey sanganabasu, ask Mass to fix this –  Sharanabasu Angadi Jun 11 '13 at 16:10

1 Answer 1

up vote 1 down vote accepted

I believe this works...

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

If you want to allow multiple values in the last dimension then change:

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

to

$output[$value['parent']][$value['middle']][] = $value['child'];
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.