array_totree( $array, $seperator = "/" ) |
Splits a given array into a tree formed hash array.
This is useful when a large array of strings needs splitting into a hierarchical array structure.
For example in incoming array structure
1 2 3 4 5 6 7 | $a = array( 'a/a/a', 'a/b/b', 'a/b/c', 'a/c/c', 'c/a/a' ); |
Is returned as:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | array( "a" => array( "a" => array( "a" => array() ), ), "b" => array( "b" => array(), "c" => array() ), "c" => array( "c" => array() ), "c" => array( "a" => array( "a" => array() ) ) ); |
The function:
?Download array_totree.php
1 2 3 4 5 6 7 8 9 10 11 12 13 | function array_totree($in, $splitchar = '/') { $out = array(); foreach ($in as $item) { $bits = explode($splitchar,$item); $outref =& $out; foreach ($bits as $bit) { if (!isset($outref[$bit])) $outref[$bit] = array(); $outref =& $outref[$bit]; } } return $out; } |