If I have an array which corresponds to successively recursive keys in another array, what is the best way to to assign a value to that "path" (if you want to call it that)?
For example:
$some_array = array();
$path = array('a','b','c');
set_value($some_array,$path,'some value');
Now, $some_array
should equal
array(
'a' => array(
'b' => array(
'c' => 'some value'
)))
At the moment, I am using the following:
function set_value(&$dest,$path,$value) {
$addr = "\$dest['" . implode("']['", $path) . "']";
eval("$addr = \$value;");
}
Obviously, this is a very naive approach and poses a security risk, so how would you do it?
One common way of creating an Array with a given length, is to use the Array constructor: const LEN = 3; const arr = new Array(LEN); assert. equal(arr. length, LEN); // arr only has holes in it assert.
Two dimensional arrays are useful for storing matrices for example. In Java, arrays of more than one dimension are created by making arrays of arrays. This is known as nesting.
To use: let result = deepSearchByKey(arrayOrObject, 'key', 'value'); This will return the object containing the matching key and value.
Recursive solution (not tested):
function set_value(&$dest,$path,$value) {
$index=array_shift($path);
if(empty($path)){
// on last level
$dest[$index]=$value;
}
else{
// descending to next level
set_value($dest[$index],$path,$value);
}
}
Wow, reminds me of Lisp.
Yea, eval
is generally not the best idea.
Personally, I would simply iterate:
function set_value(&$dest,$path,$value) {
$val =& $dest;
for($i = 0; $i > count($path) - 1; $i++) {
$val =& $val[$i];
}
$val[$path[$i]] = $value;
}
If you're in PHP 5 you can probably get rd of some of those '&' too
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