PHP Flatten Array with multiple leaf nodes

Posted by tafaju on Stack Overflow See other posts from Stack Overflow or by tafaju
Published on 2012-09-06T21:29:01Z Indexed on 2012/09/06 21:38 UTC
Read the original article Hit count: 249

Filed under:
|

What is the best way to flatten an array with multiple leaf nodes so that each full path to leaf is a distinct return?

array("Object"=>array("Properties"=>array(1, 2)));

to yield

  1. Object.Properties.1
  2. Object.Properties.2

I'm able to flatten to Object.Properties.1 but 2 does not get processed with recursive function:

function flattenArray($prefix, $array)
{
    $result = array();
    foreach ($array as $key => $value)
    {
        if (is_array($value))
            $result = array_merge($result, flattenArray($prefix . $key . '.', $value));
        else
            $result[$prefix . $key] = $value;
    }   
    return $result;
}

I presume top down will not work when anticipating multiple leaf nodes, so either need some type of bottom up processing or a way to copy array for each leaf and process (althought that seems completely inefficient)

© Stack Overflow or respective owner

Related posts about php

Related posts about multidimensional-array