$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
.
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.
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.
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.
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:
$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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With