1

I want to join the array keys to a filepath with the value at the end as file itself (the array below is a "filetree")

Array (depth, size and keynames are dynamic):

[0] => bla.tif
[1] => quux.tif
[foo] => Array (
        [bar] => Array (
                [lorem] => Array (
                        [1] => ipsum.tif
                        [2] => doler.tif
                )
        )
)
[bar] => Array (
        [qux] => Array (
                [baz] => Array (
                        [1] => ipsum.tif
                        [2] => ufo.tif
                )
        )
)

This result would be fine:

[0] => bla.tif
[1] => quux.tif
[2] => foo/bar/lorem/ipsum.tif
[3] => foo/bar/lorem/doler.tif
[4] => bar/qux/baz/ipsum.tif
[5] => bar/qux/baz/ufo.tif

Maybe there is also a pure PHP solution for that. I tried it with array_map but the results weren't fine enough.

3
  • Try it with: recursiveiterator. php.net/manual/en/class.recursivearrayiterator.php Commented Jul 15, 2014 at 15:29
  • With this structure, how would you handle the case where a directory name actually is a number? Commented Jul 15, 2014 at 15:29
  • @Yoshi, that case will not happen - all directory names are already named with letters. (This will not be changed.) Commented Jul 15, 2014 at 15:37

1 Answer 1

3

I would use a recursive function to collapse this array. Here's an example of one:

function collapse($path, $collapse, &$result)
{
  foreach($collapse AS $key => $value)
  {
    if(is_array($value))
    {
      collapse($path . $key . "/", $value, $result);
      continue;
    }
    $result[] = $path . $value;
  }
}

And here's how to use:

$result = array();
$toCollapse = /* The multidimentional array */;
collapse("", $toCollapse, $result);

and $result would contain the "imploded" array

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

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.