2

I try to found a function which build a multidimensional array after an explode.

For example : Here I create array with as explode.

$str = 'root/foo/bar/file.jpg';
$ar = explode('/', $str);

$ar => array('root', 'foo' , 'bar', 'file.jpg');

Then I want this ouput :

array(3) {
  ['root']=>
       ['foo']=>
           ['bar']=> "file.jpg"
}

Any Idea ?

Thx

Xerton Web
  • 43
  • 3
  • 3
    that's not how explode works. it takes a string and produces a SINGLE array with multiple entries representing the parts of whatever you exploded. it doesn't "go down" for you. – Marc B Jul 22 '15 at 16:40
  • @MarcB is correct, once you explode the string you will wind up with single array and to make it multi-dimensional you will have to write your own function. If you would like the pursue that option though, we'd be more than happy to help you along the way. – the_pete Jul 22 '15 at 16:44
  • 1
    I know how explode work, but I'm looking a function which converts a simple array in multidemensional array with each keys are previous array value. – Xerton Web Jul 22 '15 at 16:48

2 Answers2

1

Here is one way that this problem can be approached.

<?php

$str = 'root/foo/bar/file.jpg';

$parts = explode("/", $str);
$leaf = array_pop($parts);
$tree = array();
$branch = &$tree;
foreach($parts as $v){
    $branch[$v] = array();
    $branch = &$branch[$v];
}
$branch = $leaf;

print_r($tree);

Try it yourself here

Orangepill
  • 24,500
  • 3
  • 42
  • 63
0
<?php

$str = 'root/foo/bar/file.jpg';
//Get last part of the filename
$parts = explode('/', $str);
$last = array_pop($parts);

$arr = [];
//Create code as string to fill in array
$codeParts = implode("']['", $parts);
$codeEx = "\$arr['{$codeParts}'] = \$last;";

eval($codeEx);

var_dump($arr);

https://eval.in/403480

Output:

array(1) {
  ["root"]=>
  array(1) {
    ["foo"]=>
    array(1) {
      ["bar"]=>
      string(8) "file.jpg"
    }
  }
}
Jessica
  • 7,075
  • 28
  • 39