-2

I want to loop through an array in PHP. The loop must be recursive, because I don't now how many arrays-in-arrays there are. It is for reading translations in Symfony2.

The output format is:

a.d.e
a.f.g
b.h.i
c.j.k.l.m
c.n.o

with example array:

$array = array(
    'a' => array('d' => 'e', 'f' => 'g'),
    'b' => array('h' => 'i'),
    'c' => array(
        'j' => array(
            'k' => array(
                'l' => 'm')),
        'n' => 'o'));

I have tried the following, but this is not a final solution, but the recursion is working:

function displayArrayRecursively($array)
{
    foreach ($array as $key => $value) {

        if (is_array($value)) {
            echo $key . '<br>';
            displayArrayRecursively($value);
        } else {

            echo $key . '<br>' . $value . '<br>';       
        }
    }
}

Thanks in advance!

1
  • 1
    Sounds like you want a trie datastructure Commented Jun 17, 2014 at 9:03

3 Answers 3

3

I guess your function just output

a
d
e
...

Something like this should work :

displayArrayRecursively($array, null);

function displayArrayRecursively($array, $keysString = '')
{
    if (is_array($array)) {
        foreach ($array as $key => $value) {
            displayArrayRecursively($value, $keysString . $key . '.');
        }
    } else {
        echo $keysString . $array . '<br/> ';
    }
}

It should be pretty close to what you need.

Sign up to request clarification or add additional context in comments.

Comments

0

This function does what you want:

function displayArrayRecursively($array, $tree = array()) {
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            displayArrayRecursively($value, array_merge($tree, array($key)));
        } else {
            print implode('.', array_merge($tree, array($key, $value)));
            print "\n<br />";
        }
    }
}

Output:

a.d.e
a.f.g
b.h.i
c.j.k.l.m
c.n.o

Comments

0

Function you want

function displayArrayRecursively($array, $parent = '')
{
    foreach ($array as $key => $value) {

        if (is_array($value)) {
            if(count($value) == 1 && !empty($parent))
                $key = $parent . $key;
            displayArrayRecursively($value, $key);
        } else {
            echo $parent;
            echo $key . $value . '<br>';       
        }
    }
}

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.