Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically access values in a variably multidimensional array

$first = array("a", "b" => array("c", "d" => array("e", "f")), "g", "h" => array("f"));
$second = array("b", "d", "f");
$string = "foobar";

Given the above code, how can I set a value in $first at the indexes defined in $second to the contents of $string? Meaning, for this example, it should be $first["b"]["d"]["f"] = $string;, but the contents of $second and $first can be of any length. $second will always be one dimensional however. Here's what I had tried, which didn't seem to work as planned:

$key = "";
$ptr = $first;
for($i = 0; $i < count($second); $i++)
{
    $ptr &= $ptr[$second[$i]];
    $key = key($ptr);
}
$first[$key] = $string;

This will do $first["f"] = $string; instead of the proper multidimensional indexes. I had thought that using key would find the location within the array including the levels it had already moved down.

How can I access the proper keys dynamically? I could manage this if the number of dimensions were static.

EDIT: Also, I'd like a way to do this which does not use eval.

like image 650
Cyclone Avatar asked Sep 18 '11 23:09

Cyclone


People also ask

How to dynamically allocate two dimensional array?

A 2D array can be dynamically allocated in C using a single pointer. This means that a memory block of size row*column*dataTypeSize is allocated using malloc and pointer arithmetic can be used to access the matrix elements.

Which of the following options would you use for dynamically allocating a two dimensional array?

Using Single Pointer A single pointer can be used to dynamically allocate a 2D array in C. This means that a memory block of size row*column*dataTypeSize is allocated using malloc, and the matrix elements are accessed using pointer arithmetic.

How can you create dynamic array in C?

We can use a few C functions such as malloc, free, calloc, realloc, reallocarray to implement dynamic-sized arrays. malloc: In simple words, calling this function is equivalent to requesting OS, to allocate n bytes. If memory allocation is successful, malloc returns the pointer to the memory block.


1 Answers

It's a bit more complicated than that. You have to initialize every level if it does not exist yet. But your actual problems are:

  • The array you want to add the value to is in $ptr, not in $first.
  • $x &= $y is shorthand for $x = $x & $y (bitwise AND). What you want is x = &$y (assign by reference).

This should do it:

function assign(&$array, $keys, $value) {
    $last_key = array_pop($keys);
    $tmp = &$array;
    foreach($keys as $key) {
        if(!isset($tmp[$key]) || !is_array($tmp[$key])) {
            $tmp[$key] = array();
        }
        $tmp = &$tmp[$key];
    }
    $tmp[$last_key] = $value;
    unset($tmp);
}

Usage:

assign($first, $second, $string);

DEMO

like image 92
Felix Kling Avatar answered Sep 18 '22 08:09

Felix Kling