views:

120

answers:

3

precode: $keys = array('a', 'b', 'c', 'd'); $number = 10;

code: eval('$array[\''.implode('\'][\'',$keys).'\'] = $number;');

result:

Array (

[a] => Array
    (
        [b] => Array
            (
                [c] => Array
                    (
                        [d] => 10
                    )

            )

    )

)

problem: this is the exact result I want. Exactly! I have a list of keys and a number. The number should be set to the value of the keys array being used to generate child-based keys for a certain array (in this case called $array).

I DONT want to use eval though. I hate it. It's a hack and I want to write it proper, but after 8 hours (literally) of playing around with this, I've come to my end. A few resolutions I came up with produced this desired data set, but the nice thing about using eval us that it preserves the value of the array before hand. So it $array has some other values in it, it's not just going to overwrite them with my new keys/number. That's the part that gave me so much trouble.

Any help would be REALLY appreciate. Thanks dudes.

+3  A: 

Please note that the code below (which you evaluate) will generate a warning, and will therefore not work on projects with error reporting up to the max:

$array = array();
$array['a']['b'] = 42; // $array['a'] is not an array... yet

Since you're using PHP 5, you can work with references to manipulate your array while traversing the branch of your tree that you wish to modify.

$current = & $array;

foreach ($keys as $key):

  if (!isset($current[$key]) || !is_array($current[$key]))
    $current[$key] = array();

  $current = & $current[$key];

endforeach;

$current = $value;

Edit: corrected for avoiding warnings and conflicts.

Victor Nicollet
So why doesn't it throw an error on the second round where you effectively set `$array['a'] = $array['b']` since `a` is not an array yet either. Anyway, +1 since this works great and is way shorter than my answer.
Doug Neiner
firstly, what error does it generate? i have my reporting up the max, including deprecation warnings, and i dont see anything.your code works for cases where array is empty or with keys that aren't a potential conflict. but if the array looks like this: array('a' => 'b') and the keys looks like this array('a', 'orange') I get: Fatal error: Cannot create references to/from string offsets nor overloaded objects in ...
onassar
+1  A: 

Here is a full code example showing how it would work. Whats important is that you use a reference to the array so you can modify it:

<?php
    $keys = array('a', 'b', 'c', 'd'); 
    $number = 10;

    $org_array = array(
        "a" => "string",
        "z" => array( "k" => false)
      );

    function write_to_array(&$array, $keys, $number){
      $key = array_shift($keys);
      if(!is_array($array[$key])) $array[$key] = array();
      if(!empty($keys)){
        write_to_array($array[$key], $keys, $number);
      } else {
        $array[$key] = $number;
      }
    }

    write_to_array($org_array, $keys, $number);

    print_r($org_array);
?>
Doug Neiner
this ones the closest, but again, doesn't work for the case where the array is: array('a' => 'meow') and the keys array is: array('a', 'b', 'c').I get a Fatal error: Only variables can be passed by reference...
onassar
@onassar I misunderstood what you meant by previous values. I updated two parts in the code, the `$org_array['a']` is now set to a string to test, and I changed the `isset` test to an `is_array` test. Now if the key exists as something other than an array is is overwritten vs. extended.
Doug Neiner
you = me hero. thank you sir.
onassar
follow up: what about this case for deletion:eval('unset($array[\''.implode('\'][\'',$keys).'\']);');?
onassar
+1  A: 
function deepmagic($levels, $value)
{
    if(count($levels) > 0)
    {
        return array($levels[0] => deepmagic(array_slice($levels, 1),
            $value));
    }
    else
    {
        return $value;
    }
}

$a = deepmagic(Array('a', 'b', 'c', 'd'), 10);

var_dump($a);

Output:

array(1) {
  ["a"]=>
  array(1) {
    ["b"]=>
    array(1) {
      ["c"]=>
      array(1) {
        ["d"]=>
        int(10)
      }
    }
  }
}
Ignacio Vazquez-Abrams
That one doesn't work for array's with existing keys/values either. Hmmm.
onassar
So then use array_keys() or array_values() as desired before passing the array.
Ignacio Vazquez-Abrams