Try this:
<?php
function group($a, $level, $previous="") {
$b = [];
for( $i = 0, $n = count($a); $i < $n; ++$i ) {
if( $level > 0 && $a[$i][$level-1] !== $previous ) {
continue;
}
$key = $a[$i][$level];
$b[$key] = [];
if( array_key_exists($level+1, $a[$i]) ) {
$b[$key] = group($a, $level+1, $key);
}
}
return $b;
}
print_r(group($a, 0));
Output:
Array(
[college] => Array (
[student] => Array (
[contact] => Array ()
)
[parents] => Array (
[contact] => Array ()
)
)
[school] => Array (
[student] => Array (
[contact] => Array ()
)
[parents] => Array (
[contact] => Array ()
)
)
)
Using @AlivetoDie example:
Array (
[college] => Array (
[student] => Array (
[contact] => Array ()
)
[parents] => Array (
[contact] => Array ()
)
)
[school] => Array (
[parents] => Array (
[contact] => Array ()
)
[student] => Array (
[contact] => Array ()
)
[data] => Array (
[contact] => Array()
)
)
)
5
solved how to generate multidimensional array from array value