Home > PHP > Missing PHP Functions: array_totree()

Missing PHP Functions: array_totree()

December 13th, 2008 Leave a comment Go to comments
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:

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;
}
Categories: PHP Tags:
  1. Stephane
    September 20th, 2010 at 03:15 | #1

    Je crois bien que c est se que j ai besoin . tres heureux d avoir des ressouces top comme ca.

  1. No trackbacks yet.
*