So i get data from an api and want to save the results in an array. But the results have some arrays inside them and that data i want to iterate and add to an array.
It works to iterate the results and also the array of the results, but when i want to save the data inside a DB e.g. the first of the inner array data get saved inside the parent result perfectly, but the second entry gets the data of the first inner array and the second one and the third gets the first and second and so on. I think i do something wrong with the loops or have to clear the array after each iteration, but then i only get the last entry of the inner array in the end...
So it looks like this:
foreach($results as $result) {
// add data e.g. inside DB
foreach($result->inner as $inner) {
$inner_fields[] = [
'field_2312312' => $inner->name,
'field_3345343' => $inner->desc
];
//add data from inner_fields inside the new db entry
}
}
Why is the data from the first iteration of $inner also saved in the second iteration data?
CodePudding user response:
It's difficult to tell without the code provided, as there's no telling what your using in //add data from inner_fields inside the new db entry. However, if you're using the array there then you do need to reset/empty it:
foreach($results as $result) {
$inner_fields = [];
foreach($result->inner as $inner) {
// stuff
}
}