0

So I got this:

$tree = [
    array(
        'name' => 'One1',
    ),
    array(
        'name' => 'One2',
    ),
    array(
        'name' => 'One3',
    ),
    array(
        'name' => 'One4',
        'children' => [
            array(
                'name' => 'Two1',
            ),
            array(
                'name' => 'Two2',
                'children' => [
                    array(
                        'name' => 'Three1',
                    ),
                ],
            ),
            array(
                'name' => 'Two3',
            ),
        ]
    ),
    array(
        'name' => 'One5',
    ),
];

And I'm looking for a way to have this output (recursively):

  • One1
  • One2
  • One3
  • One4 › Two1
  • One4 › Two2 › Three1
  • One4 › Two3
  • One5

As far as I go I have this function

function getValuesPaths(array $tree, $glue = ' > ') {
    $branches = array();
    foreach ($tree as &$item) {
        $piece = $item['name'];
        if (array_key_exists('children', $item)) {
            if (count($item['children'])>1) {
                $leafs = self::getValuesPaths($item['children']);
                foreach ($leafs as $item) {
                    $branches[] = $piece . $glue . $item;
                }
            }   
        } else {
            $branches[] = $piece;
        }
    }
    return $branches;
}

This output the following paths:

  • One1
  • One2
  • One3
  • One4 > Two1
  • One4 > Two3
  • One5

It wasn't supposed to find the One4 > Two2 > Three1?

Caneco
  • 11
  • 2
  • 3
    What have you tried and where does it fail? This is not a 'write my code for me' website. – Jan Doggen Jan 06 '15 at 09:24
  • 1
    Gets you most of the way there: http://stackoverflow.com/questions/27751362/php-concatenate-cascade-multidimensional-array-keys/ – deceze Jan 06 '15 at 09:33
  • @JanDoggen sorry… I've tried some of the solutions here in _the Stack_ but many of them, like #deceze shown it's about creating the path of the keys not the values. At the moment I've melted my brain far to long trying to solve it and asked for some help. – Caneco Jan 06 '15 at 12:14

1 Answers1

2

May help you…

function getKeyPaths(array $tree, $glue = '.')
{
    $paths = array();
    foreach ($tree as $key => &$mixed) {
        if (is_array($mixed)) {
            $results = getKeyPaths($mixed, $glue);
            foreach ($results as $k => &$v) {
                $paths[$key . $glue . $k] = $v;
            }
            unset($results);
        } else {
            $paths[$key] = $mixed;
        }
    }

    return $paths;
}
C Würtz
  • 856
  • 9
  • 20