0

hello I am working with collections and arrays in laravel and now I have the following problem: after grouping a data collection I have as a result something like this:

    [
          [
             {
                "id":1,
                "number":1,
                "name":"ACTIVO",
                "type":1
             },
             {
                "id":2,
                "number":101,
                "name":"ACTIVO CORRIENTE",
                "type":1
             },
          ],
          [
             {
                "id":7,
                "number":2,
                "name":"PASIVO",
                "type":2
             }
          ]
       ]

my question is how can I remove (or join) the inner arrays and be left with a single array as follows

    [
        {
            "id":1,
            "number":1,
            "name":"ACTIVO",
            "type":1
        },
        {
            "id":2,
            "number":101,
            "name":"ACTIVO CORRIENTE",
            "type":1
        },
        {
            "id":7,
            "number":2,
            "name":"PASIVO",
            "type":2
        }
   ]

any idea how i could do this?

FeRcHo
  • 1,119
  • 5
  • 14
  • 27

2 Answers2

1
$yourArray = json_decode('[[{"id":1,"number":1,"name":"ACTIVO","type":1},{"id":2,"number":101,"name":"ACTIVO CORRIENTE","type":1}],[{"id":7,"number":2,"name":"PASIVO","type":2}]]', true);

$result = \array_merge(...$yourArray);

... - unpack all inner arrays, since array_merge accepts variadic number of arguments. So basically, you're passing each inner array as a separate argument for array_merge. Read more about arrays unpacking here.

Example with your JSON string: http://sandbox.onlinephpfunctions.com/code/3f81e329250f7d4974c38453d024c320096d3f4c

ozahorulia
  • 9,798
  • 8
  • 48
  • 72
0

Based on your dataset this should do the trick:

Solution 1:

flatten()

The flatten method flattens a multi-dimensional collection into a single dimension:

collect($data)->flatten(1)->all();

Solution 2:

collapse()

The collapse method collapses a collection of arrays into a single, flat collection:

collect($data)->collapse()->all();
steven7mwesigwa
  • 5,701
  • 3
  • 20
  • 34