Reputation: 817
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?
Upvotes: 3
Views: 361
Reputation: 1219
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.
Upvotes: 0
Reputation: 635
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.
}
Upvotes: 0
Reputation: 37365
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 } }
Upvotes: 1