Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a value in a multi-dimensional array using an array of keys

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...
    }
}
like image 766
Rob Curle Avatar asked Nov 24 '11 21:11

Rob Curle


2 Answers

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;
}
like image 84
Kaii Avatar answered Oct 16 '22 00:10

Kaii


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.

like image 20
NikiC Avatar answered Oct 16 '22 00:10

NikiC