I have a php array that stores other nested arrays. The data to be inserted into the array is sent as "a_b_c_x", "a_b_c_y", "a_b_c_z_p", "a_b_d", etc. the four strings mentioned above need to the stored in an array as:
[
a = [
b = [
c = [
x = [],
y = [],
z = [
p = []
]
],
d = []
]
]
]
The array can have unknown number of nestings. I need to parse the string to search for existing keys and add new ones. I tried something like:
foreach($productConfigurationAdd as $toAdd) {
$addArray = explode('_', $toAdd);
$addTo = &$savedConfigurations;
foreach($addArray as $addElem) {
if(array_search($addElem, $addTo) === false) {
$addTo[$addElem] = [];
$addTo = &$addTo[$addElem];
}
else {
$addTo = &$addTo[$addElem];
}
}
}
and it is only saving the first children of each block. Please let me know what is going wrong here.
Edit:
In the above code, $savedConfigurations is the array that is obtained from the database and if the add string contains new configurations, it is stored in $savedConfigurations as mentioned in the question.