0

Is it possible to create multidimensional array with its keys defined in array? Yes, it is, according to bunch of Stack Overflow answers. Here is one: Dynamic array keys

function insert_using_keys($arr, array $path, $value) { // See linked answer }
$arr = create_multi_array($arr, array('a', 'b', 'c'), 'yay'));
print_r($arr);

Prints

Array ( [a] => Array ( [b] => Array ( [c] => yay ) ) ) 

Would the same be possible for class properties?

This is a barebone version of my Collection class. Method set_at should add a multidimensional array to $data property the same way insert_using_keys function does.

class A {

    protected $data = array();

    public function set($key, $value) {
         $this->data[$key] = $value;
    }

    public function set_at(array $keys, $value) {

    }

}

I've tried a several modifications of the insert_using_keys to no avail. I was able to set the keys to the property, but not assign value "to the last one".

Would someone point me in the right direction please? Thanks in advance!

Community
  • 1
  • 1
Petr Cibulka
  • 2,452
  • 4
  • 28
  • 45

1 Answers1

0

In the midst of recreating the "key-setter" function, I was able to answer my own question (was it your intention all along, Stefan?).

Here is the code:

public function set_at(array $keys, $value) {

    $first_key = array_shift($keys);

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

    $this->data[$first_key] = $value;

}
Petr Cibulka
  • 2,452
  • 4
  • 28
  • 45