0

My input array is

$data = array(
  array('department'=>'a', 'parent'=>'0'),
  array('department'=>'b', 'parent'=>'0'),
  array('department'=>'c', 'parent'=>'0'),
  array('department'=>'aa', 'parent'=>'a'),
  array('department'=>'bb', 'parent'=>'b'),
  array('department'=>'cc', 'parent'=>'c'),
  array('department'=>'aaa', 'parent'=>'a'),
  array('department'=>'bbb', 'parent'=>'b'),
  array('department'=>'ccc', 'parent'=>'c'), 
  array('department'=>'aa1', 'parent'=>'aa'),
  array('department'=>'bb1', 'parent'=>'bb'),
  array('department'=>'cc1', 'parent'=>'cc'),
  array('department'=>'aa2', 'parent'=>'aa'),
  array('department'=>'bb2', 'parent'=>'bb'),
  array('department'=>'cc2', 'parent'=>'cc'),

);

I want to convert above array into like below array.

$result = array(
'a' => array('aa'=> array('aa1','aa2'),'aaa'),
'b' => array('bb'=> array('bb1','bb2'),'bbb'),
'c' => array('cc'=> array('cc1','cc2'),'ccc'),
);

What is the best way to do it?

w3father
  • 569
  • 2
  • 11
  • 26

1 Answers1

1

Bit complicated to be honest. There are a couple of questions here in SO that address similar problems. The best way to go about this problem (in my opinion) is to build a Tree.

Build a tree from a flat array in PHP

create array tree from array list

Using answers from this questions I came up with a solution that might suit you.

In the first place, I build a Tree using code provided in those answers. Unfortunately, in order to build the tree properly you have to have the 'department' field in every subarray and the resultant array doesn't have the required structured. That's the reason why I added a second method that goes recursively over the Tree to give it the desired format.

$new = array();
foreach ($data as $a) {
    $parent = $a['parent'];
    unset($a['parent']);// We don't need this anymore
    $new[$parent][] = $a;
}
$tree = giveMeFormattedArray($new, $new[0]); // changed
print_r($tree);

function giveMeFormattedArray($a, $ele) {
    $arr = createTree($a, $ele);// Create the Tree in the first place.
    return parseTree($arr);// Parse the result and return the desired format.
}

function parseTree(&$arr) {
    $res = array();
    foreach($arr as $key => $el) {
        $res[$key] = isset($el["children"]) ? parseTree($el["children"]) : $el["department"];
    }
    return $res;
}

function createTree(&$list, $parent) {
    $tree = array();
    foreach ($parent as $k => $l) {
        if (isset($list[$l['department']])) {
            $l['children'] = createTree($list, $list[$l['department']]);
        }
        $tree[$l['department']] = $l;
    }
    return $tree;
}
Community
  • 1
  • 1
acontell
  • 6,792
  • 1
  • 19
  • 32