Home > Enterprise >  merge two arrays into one Laravel PHP
merge two arrays into one Laravel PHP

Time:12-21

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?

CodePudding user response:

$yourArray = json_decde('[[{"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

CodePudding user response:

According to laravel documentation you can merge two collections with merge method

$collection = collect(['product_id' => 1, 'price' => 100]);
$merged = $collection->merge(['price' => 200, 'discount' => false]);
$merged->all();

and check replace method could be helpful

  • Related