1

I have a function that generates a multidimensional to represent a tree structure. A print_r of what it returns looks something like this:

Array (
    [A] => Array (
        [A1] =>
        [A2] =>
    )
    [B] => Array (
        [B1] => Array (
            [B1a] =>
        )
    )
)

What I need is a recursive function that output this in depth first order, like this:

A
  A1
  A2
B
  B1
    B1a

or just

A, A1, A2, B, B1, B1a

I have tried to solve this for hours now so please help me.

3 Answers 3

1

use recursive function eg:

<?php
$arr = array(
    'A'=>array(
        "A1"=>1,
        "A2"=>1,
        ),
        "B"=>array(
            "B1"=>array(
                "B2a"=>1,
                )
            ),
    );

function print_key($arr, $depth = 0){
    $pre_str = str_repeat("\t", $depth);
    foreach($arr as $k=>$v){
        echo $pre_str.$k."\n";
        if(is_array($v))
            print_key($v, $depth+1);
    }
}
print_key($arr);
Sign up to request clarification or add additional context in comments.

1 Comment

sometimes we get stuck,heng;)
1

You don't need to recursively scan the array, since print_r already does it for you. You could just call print_r and then parse the output:

preg_match_all('/^[^\[]*\[([^\]]*)\][^\]]*$/m', print_r($arr, true), $matches);
$result = implode(', ', $matches[1]);

echo $result; // A, A1, A2, B, B1, B1a

Demo

1 Comment

Clever! I like the simplicity but i'll go for the recursive solution if i need to mark up the result or make other more complex changes later on. Still like this one though. Thanks!
0

I realized I can just try to mimic the print_r function so I found a useable function here: php print_r nice table

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.