I have recently started adding Angular to an old app I made. Part of the app stores a json encoded array in a single cell in a mySql table. I know this is frowned upon, but I'm 100% sure it won't come back to bite me later. In the past I've just been able to do a json_decode on the array and output the values in an ordered list. Since I've included Angular, the data is being encoded and echoed at the end of the php file. It is then picked up by the Angular code and I'm able to loop through this deeply nested multidimensional object until it gets to this part...
"sub_items":"[\"subOne\",\"subTwo\",\"subThree\"]"
The closest I can get is to output the string including all the backslashes, brackets and quotes which makes sense because it is a string.
I've tried doing a json_decode on every instance of sub_items, but it's not working. I think that's because the whole thing just gets encoded again.
How might I be able to loop through this array?
EDIT
I have made some progress with the following based on comments in the answer from @Yaser Adel Mehraban.
foreach($master as $index => $item) {
if($category == $item['category']) {
$sub = [];
$sub['sub_items'] = json_decode($item['sub_items']);
unset($item['sub_items']);
array_push($items, $item, $sub);
}
}
This returns
...created_at":"2016-11-01 14:19:07"},{"sub_items":["subOne","subTwo","subThree"...
The formatting of the array I was having trouble with is correct now I think, but it's sitting outside the item. I have tried to array_merge as well, but it adds a new key which would force an unnecessary ng-repeat to step down I think. Suggestions...
UPDATED:
You should decode using array options and then iterate through them using ng-repeat, however to get decode working you first need to split your string and get the second part:
$subItemsStr = explode('"sub_items":"[\"subOne\",\"subTwo\",\"subThree\"]"')[1];
$subItems = json_decode($subItemsStr, true);
Then you can use it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With