In relation to this question i asked earlier: Searching multi-dimensional array's keys using a another array
I'd like a way to set a value in a multi-dimensional array (up to 6 levels deep), using a seperate array containing the keys to use.
e.g.
$keys = Array ('A', 'A2', 'A22', 'A221');
$cats[A][A2][A22][A221] = $val;
I tried writing a clumsy switch with little success... is there a better solution?
function set_catid(&$cats, $keys, $val) {
switch (count($keys)) {
case 1: $cats[$keys[0]]=$val; break;
case 2: $cats[$keys[0]][$keys[1]]=$val; break;
case 3: $cats[$keys[0]][$keys[1]][$keys[2]]=$val; break;
etc...
}
}
try this:
function set_catid(&$cats, $keys, $val) {
$ref =& $cats;
foreach ($keys as $key) {
if (!is_array($ref[$key])) {
$ref[$key] = array();
}
$ref =& $ref[$key];
}
$ref = $val;
}
function insertValueByPath($array, $path, $value) {
$current = &$array;
foreach (explode('/', $path) as $part) {
$current = &$current[$part];
}
$current = $value;
return $array;
}
$array = insertValueByPath($array, 'A/B/C', 'D');
// => $array['A']['B']['C'] = 'D';
You can obviously also use an array for $path
by just dropping the explode
call.
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