My JSON output is:
{
"follow_carts":[
{
"id":1,
"user_id":10001,
"created_at":null,
"updated_at":null,
"followings":[
{
"id":1,
"name":"Dr. Timmy Kulas Sr.",
"email":"[email protected]",
"email_verified_at":"2022-09-15T16:17:07.000000Z",
"created_at":"2022-09-15T16:17:08.000000Z",
"updated_at":"2022-09-15T16:17:08.000000Z",
"user_type":"vendor",
"pivot":{
"follower_id":1,
"user_id":1
},
"carts":[
{
"id":1,
"user_id":1,
"level_two_id":1,
"cart_name":"Lorem lipsum",
"main_photo":"https://images.pexels.com/photos/2533311/pexels-photo-2533311.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2",
"important_details":"york",
"created_at":null,
"updated_at":null,
"status":1,
"main_category_id":1,
"opens":1
},
{
"id":2,
"user_id":1,
"level_two_id":2,
"cart_name":"Cafe",
"main_photo":"https://images.pexels.com/photos/2533311/pexels-photo-2533311.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2",
"important_details":"New York's best cafe",
"created_at":null,
"updated_at":null,
"status":0,
"main_category_id":1,
"opens":2
}
]
}
]
}
]
}
I am trying to get total "opens" of all carts of each follow_carts. So in this case the result should be 2 1 = 3 opens.
I want to do it using collection sum but no luck.
Can anyone please give me an idea.
CodePudding user response:
If this structure remain same if follow carts remains same then you can use below
$data = collect($jsonData); //convert json data into array
$value = collect($data['follow_carts'][0]['followings'][0]['carts']);
$sum = $value->sum('opens');
if follow_carts are multiple then you have to use foreach loop and follow the same process.
CodePudding user response:
You can use a for loop on your json !
$s=0;
foreach($data["follow_carts"][0]["followings"][0]['carts'] as $value){
$s = $value["opens"];
}