Each input array is like a branch with a leaf at the end. We pass it one by one, creating, if necessary, sub-arrays for all elements except the last. Last insert as value.
Passing the next node, see if it already exists as a petal (value, not a key), and, if there is, translate it into an array:
$a1 = array(279171, 438170); $a2 = array(279171, 438156, 438157); $a3 = array(279171, 438178); $a4 = array(279172, 436113, 436115); $a5 = array(279172, 436113, 438108); $input = array($a1, $a2, $a3, $a4, $a5); $result = array(); foreach( $input as $item) { pushBranch( $item, $result); } function pushBranch( $arr, &$result) { $len = count( $arr); for($i=0, $cursor = &$result; $i<$len; $i++) { $el = $arr[ $i]; if( $i === $len-1 // last && !array_key_exists( $el, $cursor) && false === array_search( $el, $cursor, true)) { array_push( $cursor, $el); } else { // middle if( array_key_exists( $el, $cursor)) { $cursor = &$cursor[ $el]; } else { $key = array_search( $el, $cursor, true); if( false !== $key) unset( $cursor[ $key]); $cursor[ $el] = array(); $cursor = &$cursor[ $el]; } } } } print_r( $result);
Result:
Array ( [279171] => Array ( [0] => 438170 [438156] => Array ( [0] => 438157 ) [438157] => 438178 ) [279172] => Array ( [436113] => Array ( [0] => 436115 [1] => 438108 ) ) )
Ideone