'Need array of specificed key which exists within array of array
So here is the data format in JSON. I need an array which contains all the array within "data_array".There can be multiple items in "main_array".Is there any way to do this without using any loop.Thank you
{
"id" : "60561bbd1be6cb1972254ec4",
"main_array": [
{
"data_array": [
{
"_id": "6054d5c3dbd0af1cca71b857",
"qty" : 2000
}
]
},
{
"data_array": [
{
"_id": "6054d5c3dbd0af1cca71b859",
"qty" : 78970
},
{
"_id": "6054d5c3dbd0af1cca71b860",
"qty" : 978
}
]
}
]
}
This is the expected array
[
{
"_id": "6054d5c3dbd0af1cca71b857",
"qty" : 2000
},
{
"id": "6054d5c3dbd0af1cca71b859",
"qty" : 78970
},
{
"_id": "6054d5c3dbd0af1cca71b860",
"qty" : 978
}
]
Currently I'm doing this
$expectedArray = [];
foreach($inputs['main_array'] as $mainArray){
$expectedArray =array_merge($expectedArray,$mainArray['data_array']);
}
Solution 1:[1]
I got the answer to this question from here https://laracasts.com/discuss/channels/laravel/need-array-of-specificed-key-which-exists-within-array-of-array?page=1&replyId=771482
As I'm already getting converted data in array form.I removed json_decode().
$collect = collect($inputs['main_array']);
$data = $collect->pluck('data_array');
$flat = collect($data)->flatten(1);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Shalini Singh |
