Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create dynamic multidimensional array

Tags:

arrays

php

I'm trying to create an array while parsing a string separated with dots

$string = "foo.bar.baz";
$value = 5

to

$arr['foo']['bar']['baz'] = 5;

I parsed the keys with

$keys = explode(".",$string);

How could I do this?

like image 673
Paté Avatar asked Oct 10 '22 14:10

Paté


2 Answers

You can do:

$keys = explode(".",$string);
$last = array_pop($keys);

$array = array();
$current = &$array;

foreach($keys as $key) {
    $current[$key] = array();
    $current = &$current[$key];
}

$current[$last] = $value;

DEMO

You can easily make a function out if this, passing the string and the value as parameter and returning the array.

like image 82
Felix Kling Avatar answered Oct 13 '22 10:10

Felix Kling


You can try following solution:

function arrayByString($path, $value) {
  $keys   = array_reverse(explode(".",$path));

  foreach ( $keys as $key ) {
    $value = array($key => $value);
  }

  return $value;
}

$result = arrayByString("foo.bar.baz", 5);

/*
array(1) {
  ["foo"]=>
  array(1) {
    ["bar"]=>
    array(1) {
      ["baz"]=>
      int(5)
    }
  }
}
*/
like image 36
hsz Avatar answered Oct 13 '22 09:10

hsz