phparraysmultidimensional-arrayhierarchical-datadirectory-structure

Convert flat array of delimited strings (filepaths) to a hierarchical, associative multidimensional array


I have a collection of keys in this massive flat single array I would like to basically expand that array into a multidimensional one organized by keys - here is an example:

Input:

[
    'invoice/products/data/item1',
    'invoice/products/data/item2',
    'invoice/products/data/item2',
]

Desired result:

[
    'invoice' => [
        'products' => ['item1', 'item2', 'item3']
    ]
]

How can I do this?

The length of the above strings are variable.


Solution

  • Something along these lines: (Didn't test it though!) Works now ;)

    $data = array();
    $current = &$data;
    foreach($keys as $value) {
      $parts = explode("/", $value);
      $parts_count = count($parts);
      foreach($parts as $i => $part) {
        if(!array_key_exists($part, $current)) {
          if($i == $parts_count - 1) {
            $current[] = $part;
          }
          else {
            $current[$part] = array();
            $current = &$current[$part];
          }
        }
        else {
          $current = &$current[$part];
        }
      }
      $current = &$data;
    }
    

    $keys beeing the flat array.