简体   繁体   中英

PHP - dynamically add dimensions to array

I have a :

$value = "val";

I also have an array :

$keys = ['key1', 'key2', 'key3'...]

The keys in that array are dynamically generated, and can go from 2 to 10 or more entries.

My goal is getting this :

$array['key1']['key2']['key3']... = $value;

How can I do that ?

Thanks

The easiest, and least messy way (ie not using references) would be to use a recursive function:

function addArrayLevels(array $keys, array $target)
{
      if ($keys) {
          $key = array_shift($keys);
          $target[$key] = addArrayLevels($keys, []);
      }
      return $target;
}

//usage
$keys = range(1, 10);
$subArrays = addARrayLevels($keys, []);

It works as you can see here .

How it works is really quite simple:

  • if ($keys) { : if there's a key left to be added
  • $key = array_shift($keys); shift the first element from the array
  • $target[$key] = addArrayLevels($keys, []); : add the index to $target , and call the same function again with $keys (after having removed the first value). These recursive calls will go on until $keys is empty, and the function simply returns an empty array

The downsides:

  • Recursion can be tricky to get your head round at first, especially in complex functions, in code you didn't write, but document it well and you should be fine

The pro's:

  • It's more flexible (you can use $target as a sort of default/final assignment variable, with little effort (will add example below if I find the time)
  • No reference mess and risks to deal with

Example using adaptation of the function above to assign value at "lowest" level:

function addArrayLevels(array $keys, $value)
{
      $return = [];
      $key = array_shift($keys);
      if ($keys) {
          $return[$key] = addArrayLevels($keys, $value);
      } else {
          $return[$key] = $value;
      }
      return $return;
}

$keys = range(1, 10);
$subArrays = addARrayLevels($keys, 'innerValue');
var_dump($subArrays);

Demo

I don't think that there is built-in function for that but you can do that with simple foreach and references.

$newArray = [];
$keys = ['key1', 'key2', 'key3'];
$reference =& $newArray;

foreach ($keys as $key) {
    $reference[$key] = [];

    $reference =& $reference[$key];
}

unset($reference);

var_dump($newArray);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM