Skip to main content
Stack Overflow
  1. About
  2. For Teams

Return to Revisions

9 of 9
Commonmark migration

How to access and manipulate multi-dimensional array by key names / path?

I've to implement a setter in PHP, that allows me to specify the key, or sub key, of an array (the target), passing the name as a dot-separated-keys value.

Given the following code:

$arr = array('a' => 1,
 'b' => array(
 'y' => 2,
 'x' => array('z' => 5, 'w' => 'abc')
 ),
 'c' => null);
$key = 'b.x.z';
$path = explode('.', $key);

From the value of $key I want to reach the value 5 of $arr['b']['x']['z'].

Now, given a variable value of $key and a different $arr value (with different deepness).

How can I set the value of the element referred by by $key?

For the getter get() I wrote this code:

public static function get($name, $default = null)
{
 $setting_path = explode('.', $name);
 $val = $this->settings;
 foreach ($setting_path as $key) {
 if(array_key_exists($key, $val)) {
 $val = $val[$key];
 } else {
 $val = $default;
 break;
 }
 }
 return $val;
}

To write a setter is more difficult because I succeed in reaching the right element (from the $key), but I am not able to set the value in the original array and I don't know how to specify the keys all at once.

Should I use some kind of backtracking? Or can I avoid it?

Kamafeather
  • 10.1k
  • 15
  • 80
  • 111
lang-php

AltStyle によって変換されたページ (->オリジナル) /