3

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?

hakre
  • 193,403
  • 52
  • 435
  • 836
raj
  • 819
  • 5
  • 9
  • 2
    Why do that conversion? Just use recursive iterator on directory and you'll get your array – Alma Do Feb 04 '14 at 09:51
  • You mentioned that you want to convert directory to array. So use iterator for that – Alma Do Feb 04 '14 at 09:55
  • My input is strings from a log file. An example? – raj Feb 04 '14 at 10:03
  • possible duplicate of [Variable containing a path as a string to multi-dimensional array?](http://stackoverflow.com/questions/3857033/variable-containing-a-path-as-a-string-to-multi-dimensional-array) or [preg_split string to multidimensional array](http://stackoverflow.com/q/7651351/367456) or [Multidimensional array from string](http://stackoverflow.com/q/10123604/367456) – hakre Feb 16 '14 at 00:52

3 Answers3

1

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
  }
}
Alma Do
  • 37,009
  • 9
  • 76
  • 105
0

Read the log file line by line:

$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.
}
BogdanM
  • 625
  • 1
  • 6
  • 10
0

Try below code:

<?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 line of your data.

kwelsan
  • 1,229
  • 1
  • 7
  • 18