Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert directory structure into assoc array

I have a strings like the following

abc\xyz
abc\def\ghi

And I need it in the assoc array formats

$array["abc"]["xyz"]
$array["abc"]["def"]["ghi"]

I am exploding the string by "\" character.

Now I have an array for each line. From this how do I dynamically get the above assoc format?

like image 609
raj Avatar asked Dec 02 '25 02:12

raj


1 Answers

Since you're clarified that your data is derived from some log-file (i.e. not from FS directly, so it may be even non-real directory), you may use this simple method to get your array:

$data = 'abc\xyz
abc\def\ghi
abc\xyz\pqr';
//
$data = preg_split('/[\r\n]+/', $data);
$result  = [];
$pointer = &$result;
foreach($data as $path)
{
   $path = explode('\\', $path);
   foreach($path as $key)
   {
      if(!isset($pointer[$key]))
      {
         $pointer[$key] = null;
         $pointer = &$pointer[$key];
      }    
   }
   $pointer = &$result;
}

-this will result in:

array(3) {
  ["abc"]=>
  array(1) {
    ["xyz"]=>
    NULL
  }
  ["def"]=>
  array(1) {
    ["ghi"]=>
    NULL
  }
  ["xyz"]=>
  array(1) {
    ["pqr"]=>
    NULL
  }
}
like image 150
Alma Do Avatar answered Dec 03 '25 15:12

Alma Do



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!