Tell me how easy it is to make replacing arrays in a multidimensional array.

There is a config from a file in JSON , I decode it and at the output I get this array.

  Array ( [name] => Tables conf [databases] => Array ( [0] => Array ( [name] => DB1 [tables] => Array ( [0] => Array ( [name] => table1 ) [1] => Array ( [name] => table2 ) [2] => Array ( [name] => table3 ) ) ) ) ) 

And there is also a new configuration of the form:

 Array ( [databases] => Array ( [0] => Array ( [name] => DB1 [tables] => Array ( [0] => Array ( [tbl_name] => table1 ) [1] => Array ( [tbl_name] => table2 ) [2] => Array ( [tbl_name] => table3 ) ) ) [1] => Array ( [name] => DB2 [tables] => Array ( [0] => Array ( [tbl_name] => table2 ) [1] => Array ( [tbl_name] => table3 ) ) ) ) ) 

It is as simple as possible to implement a new config into the old one without overwriting the entire old one, but only change some array by key or add a new one, that is, replace the entire DB1 with a new DB1 or add DB2 .

I tried this option, it works, I would like to know how to make it easier.

 $config = $_POST['config']; $filteredConfig = array_filter($config['databases'], function($val, $key){ return !empty($val['tables']); }, ARRAY_FILTER_USE_BOTH); $fileConfig = file_get_contents('conf/tables_config_vars.json'); $fileConfig = json_decode($fileConfig, true); foreach($fileConfig['databases'] as $key => $val){ foreach($filteredConfig as $confKey => $confVal){ if($val['name'] == $confVal['name']){ unset($fileConfig['databases'][$key]); $fileConfig['databases'][] = $confVal; } } } 

    1 answer 1

    Something like this:

     function mergeConfig(array &$config, array $addConfig) { foreach ($addConfig as $key => $value) { if (isset($config[$key]) && is_array($config[$key])) { is_array($value) ? $this->mergeConfig($config[$key], $value) : array_push($config[$key], $value); } else { $config[$key] = $value; } } } 

    where $ config is the base and the resulting config, to which you need to add another; $ addConfig - config to add