2

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']);
}
6
  • 2
    Not sure quite what you mean by I need a collective array of data_array Commented Feb 10, 2022 at 12:41
  • Is there a reason you want to avoid looping? Commented Feb 10, 2022 at 12:43
  • @RiggsFolly Added the expected response Commented Feb 10, 2022 at 12:47
  • @ChrisHaas There is no specific reason I'm looking for better and faster way to do this to reduce the time because it will have large amount of data. Commented Feb 10, 2022 at 12:48
  • “Better and faster” implies you have a way you are doing this already. Can you post that code? Commented Feb 10, 2022 at 12:51

1 Answer 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);
Sign up to request clarification or add additional context in comments.

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.