PHP set dynamic array index
arrays, php
Solution
I think you are looking for this
function set_value($object, $paths, $value, $index){
$key = $paths[$index];
$sub_object = $object[$key];
if (!is_array($sub_object)){
$object[$key] = $value;
}else{
$index = $index+1;
$object[$key] = set_value($sub_object, $paths, $value, $index);
}
return $object;
}
Problem
I have the following `key/value` from my `$_POST` variable: ``` Array ( 'translations_0_comment' => 'Greetings from UK' ) ``` What I would like is to set this values to the following array ``` $data[translations][0][comment] = 'Greetings from UK'; ``` So the idea is that I can have anything in my `KEY` values, and from that I will populate an array. Is there any safe way to do this without using `eval()` ? All help is appreciated. UPDATE: this would be the idea with `eval()` ``` foreach ($_POST as $key => $dataValue) { $a = explode("_", $key); $builder = '$object'; foreach ($a as $value) { $builder.='['.$value.']'; } $builder.=' = '.$dataValue.';'; eval($builder); } ```