CodeBrauer
CodeBrauer

Reputation: 2925

Implode an multidimensional array by keys and values with PHP

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.

Upvotes: 1

Views: 942

Answers (1)

Kodlee Yin
Kodlee Yin

Reputation: 1089

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

Upvotes: 3

Related Questions