$out_data = array(
'home' => ['city' => 'Miami', 'state' => 'FL', 'location' => ['lat' => '40.00', 'long' => '50.00']],
'work' => ['main' => ['role' => 'cheif', 'address' => 'Miami, FL'], 'hobby' => ['role' => 'painter', 'address' => null]],
'age' => 68
);
echo $out_data['age'];
print_r($out_data['home']['location']);
$out_data['work']['new'] = ['role' => 'new_work_role', 'address' => 'homeland'];
print_r($out_data['work']['new']);
$out_data = array(
'home' => ['city' => 'Miami', 'state' => 'FL', 'location' => ['lat' => '40.00', 'long' => '50.00']],
'work' => ['main' => ['role' => 'cheif', 'address' => 'Miami, FL'], 'hobby' => ['role' => 'painter', 'address' => null]],
'age' => 68
);
function get_data($data, $param) {
$param = explode('\\', $param);
$result = $data[$param[0]];
for ($i = 1; $i < count($param); $i++) {
$result = $result[$param[$i]];
}
return $result;
}
print_r(get_data($out_data, 'age'));
print_r(get_data($out_data, 'home\location'));
print_r(get_data($out_data, 'work\main\address'));
function set_data(&$arr, $data, $param) {
$param = explode('\\', $param);
$result = &$arr[$param[0]];
for ($i = 1; $i < count($param); $i++) {
$result = &$result[$param[$i]];
}
$result = $data;
}
set_data($out_data, ['role' => 'boss', 'address' => 'Secret Base 1'], 'work\main\secret_job\project_1\state\city\street');
print_r($out_data);
Array
(
[home] => Array
(
[city] => Miami
[state] => FL
[location] => Array
(
[lat] => 40.00
[long] => 50.00
)
)
[work] => Array
(
[main] => Array
(
[role] => cheif
[address] => Miami, FL
[secret_job] => Array
(
[project_1] => Array
(
[state] => Array
(
[city] => Array
(
[street] => Array
(
[role] => boss
[address] => Secret Base 1
)
)
)
)
)
)
[hobby] => Array
(
[role] => painter
[address] =>
)
)
[age] => 68
)
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];
}
}
}