zwitterion zwitterion - 6 months ago 15
PHP Question

PHP - How to properly merge 2 arrays multi level in this example?

I have the follow array:

$arrIni["ENV"]="US";
$arrIni["sap_db_server"] = "192.xxx.x.xx";

$arrIni["local_db_server"] = "localhost";
$arrIni["local_db_username"] = "root";

//Default settings
$arrIni["arrEnvSettings"]["UserTypeID"]=4;
$arrIni["arrEnvSettings"]["LocalizationID"]=1;
$arrIni["arrEnvSettings"]["LangLabels"] = array();
$arrIni["arrEnvSettings"]["pages"]["st1"]="st1.php";
$arrIni["arrEnvSettings"]["pages"]["st2"]="st2.php";
$arrIni["arrEnvSettings"]["pages"]["st3"]="st3.php";


And I want to merge with this one:

$setParam["arrEnvSettings"]["pages"]["st3"]="st3_V2.php";


This is what I am doing:

echo "<pre>";
print_r(array_merge($arrIni,$setParam));
echo "</pre>";


And this is what I am getting:

Array
(
[ENV] => US
[sap_db_server] => 192.xxx.x.xx
[local_db_server] => localhost
[local_db_username] => root
[arrEnvSettings] => Array
(
[pages] => Array
(
[st3] => st3_V2.php
)

)

)


In the php doc about merge, this is the comment
" ...If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. ..."


So in this way, I suppose to get this output instead of the last one:

Array
(
[ENV] => US
[sap_db_server] => 192.xxx.x.xx
[local_db_server] => localhost
[local_db_username] => root
[arrEnvSettings] => Array
(
[UserTypeID] => 4
[LocalizationID] => 1
[LangLabels] => Array
(
)

[pages] => Array
(
[st1] => st1.php
[st2] => st2.php
[st3] => st3_V2.php
)

)

)


I do not understand why
$setParam["arrEnvSettings"]["pages"]["st3"]
is overriding the entire
$arrIni["arrEnvSettings"]
.

Note:

If I use
array_merge_recursive($arrIni,$setParam))
I will have the follow result but it is not what I want.

Array
(
[ENV] => US
[sap_db_server] => 192.xxx.x.xx
[local_db_server] => localhost
[local_db_username] => root
[arrEnvSettings] => Array
(
[UserTypeID] => 4
[LocalizationID] => 1
[LangLabels] => Array
(
)

[pages] => Array
(
[st1] => st1.php
[st2] => st2.php
[st3] => Array
(
[0] => st3.php
[1] => st3_V2.php
)

)

)

)


Is there a way to do this without iterate over the array? Only using merging? What am I doing wrong?

Answer

This should do the trick:

array_replace_recursive($arrIni,$setParam);