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

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. Commented Jul 22, 2015 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. Commented Jul 22, 2015 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. Commented Jul 22, 2015 at 16:48

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Really like your answer but I guess you made a little typo. $branch[$v] = $leaf; should be $branch = $leaf;
@PHPhil thanks caught and fixed it in the 3v4l link but not in the answer.
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"
    }
  }
}

6 Comments

While inventive using eval here is probably a bad idea
With this exact code, I don't see how it can be harmful. If the OP has no control over the strings being exploded or there's more info, then yes, it could cause problems. Could use a link on the dangers of eval.
How about not using eval for no other reason than you shouldn't need the extra overhead to assign an array element a value?
From Rasmus' own mouth If eval() is the answer, you're almost certainly asking the wrong question. -- Rasmus Lerdorf, BDFL of PHP
@Orangepill I agree completely. But I didn't write the question.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.