How can I return multidimensional array keys in tree format in PHP?
For example, if I have the following array:
$array = array (
array (
'name' => 'A',
'product' => array (
'qty' => 1,
'brand' => 'Tim'
),
'goods' => array (
'qty' => 2
),
'brand' => 'Lin'
),
array (
'name' => 'B',
'product' => array (
'qty' => 6,
'brand' => 'Coff'
),
'goods' => array (
'qty' => 4
),
'brand' => 'Ji'
)
);
How can I get a result like the following -- including no repeating of keys:
-name
-product
--qty
--brand
-goods
--qty
--brand
Recursive functions should cover any depth you want/need:
function print_tree($tree, $level = 0) {
foreach($tree AS $name => $node) {
if(
is_scalar($node) OR
(
is_object($node) AND
method_exists($node, '__toString')
)
) {
echo str_repeat('-', $level).$name.': '.$node;
}
else if(
is_array($node) OR
(
is_object($node) AND
$node InstanceOf Traversable
)
) {
echo str_repeat('-', $level).$name.":\n";
print_tree($node, $level+1);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With