0

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.

2
  • follows_cart is multiple or single? Commented Sep 21, 2022 at 9:27
  • and what have you tried so far ? Commented Sep 21, 2022 at 9:47

2 Answers 2

0

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Follow_carts are array
Following also an array
did you try solution will it work? or you need something else?
0

You can use a for loop on your json !

$s=0;
foreach($data["follow_carts"][0]["followings"][0]['carts'] as $value){
  $s += $value["opens"];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.