Convert directory structure to array

I have lines like

abc\xyz
abc\def\ghi

And I need it in associative array formats

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

I insert the string with the character "\".

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

+3
source share
3 answers

Since you found out that your data was obtained from some log file (i.e. not from FS directly, so it may not even be a real directory), you can 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 lead to:

array (3) {
  ["abc"] =>
  array (1) {
    ["xyz"] =>
    Null
  }
  ["def"] =>
  array (1) {
    ["ghi"] =>
    Null
  }
  ["xyz"] =>
  array (1) {
    ["pqr"] =>
    Null
  }
}
+1

:

$yourAssoc = array();
$handle = fopen("inputfile.txt", "r");
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        // process the line read.
        $arrayLine = explode('/', $line);
        if (!in_array($arrayLine[0], $yourAssoc)) {
            $yourAssoc[$arrayLine[0]] = 'stuff'; // you take it from here and do what you want
        }
    }
} else {
    // error opening the file.
}
0

:

<?php
$varStr = 'abc\def\ghi';

$arr = explode("\\", $varStr);
$outArr = array();

foreach (array_reverse($arr) as $arr)
    $outArr = array($arr => $outArr);


print_r($outArr);

Note. I used only one row of data.

0
source

All Articles