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?
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With