1

I have string $s = 'controller/front/home';

value $v = "some value";

and array $a = [];

What is the best way to make multidimensional array like that?

$a['controller']['front']['home'] = $v;

[edit]

I don't know how many parts (separated by /) string $s can have, so manual array building by exploded parts is the last option I would consider.

Robert
  • 372
  • 1
  • 4
  • 11
  • 2
    what you actually trying to do? Show your code efforts also.... – Nidhi May 23 '17 at 12:19
  • `$a = $v; foreach (array_reverse(explode('/', $s)) as $i) $a = array($i => $a);` – Code4R7 May 23 '17 at 13:05
  • This question has the same topic with you https://stackoverflow.com/questions/9627252/php-make-multi-dimensional-associative-array-from-a-delimited-string – rheeantz May 23 '17 at 13:06

3 Answers3

2
$a = $v; foreach (array_reverse(explode('/', $s)) as $i) $a = array($i => $a);
Code4R7
  • 2,600
  • 1
  • 19
  • 42
2

I've found this after a small research:

By this article, I've adapted it to following

$path = 'controller/front/home';
$value = 'some value';

$parts = explode('/', $path);

$arrayPath = [];

$temp = &$arrayPath;
foreach($parts as $part) {
    if(!isset($temp[$part])) {
        $temp[$part] = [];
    }
    $temp = &$temp[$part];
}
$temp = $value;

var_dump($arrayPath);

Prints:

array (size=1)
  'controller' => 
    array (size=1)
      'front' => 
        array (size=1)
          'home' => string 'some value' (length=10)
bnxuq
  • 214
  • 1
  • 9
0

You can do it like this

   $array = explode('/', $s);

and then :

  $a[$array[0]][$array[1]][$array[2]] = $v;
Bara' ayyash
  • 1,913
  • 1
  • 15
  • 25