Answer the question
In order to leave comments, you need to log in
Adding data to multidimensional array to any depth?
There is an array of unlimited nesting, for example:
$storage = [
'people' => ['Name' => 'Bill' , 'Surname' => 'Milligan', 'age' => '32', 'sex' => 'male',
'children' => ['name' => 'Sara', 'surname' => 'Milligan', 'age' => '10', 'sex' => 'female', 'mother' => 'Megan Milligan',
'schools' => ['first' => ['name' => 'Priston School', 'address' => 'USA']]]
]
];
function set($param, $data){
}
$storage['people']['children']['schools']['second'] = ['name' => 'Second School', 'address' => 'USA'];
Answer the question
In order to leave comments, you need to log in
function set_array_value(&$array, $key, $value){
if(!is_array($key)){
$key = explode('\\', $key);
}
$currentKey = array_shift($key);
if(!is_array($array[$currentKey])){
if(!isset($array[$currentKey])){
$array[$currentKey] = [];
} else {
$array[$currentKey] = [ $array[$currentKey]];
}
}
if(count($key) > 0){
set_array_value($array[$currentKey], $key, $value);
} else {
if(is_array($array[$currentKey])){
$array[$currentKey][] = $value;
} else {
$array[$currentKey] = [$array[$currentKey], $value];
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question