Search code examples
phparrayslaravelcollections

Merge array inside different collections inside same array


I am getting an array with collections and inside those collections there are arrays again. what i want to do is merge the collections to have just one collection with all the arrays of the multiple collection.

Collection {#1592 ▼
  #items: array:4 [▼
    0 => Collection {#1595 ▼
      #items: array:2 [▶]
    }
    1 => Collection {#1589 ▶}
    2 => Collection {#1585 ▼
      #items: array:2 [▶]
    }
    3 => Collection {#1579 ▼
      #items: array:2 [▶]
    }
  ]
}

Solution

  • You can use the flatten() method of collections:

    ie)

    $a = collect(['a', 'b', 'c']);
    $d = collect(['d', 'e', 'f']);
    $g = collect(['g', 'h', 'i']);
    
    $c = collect([$a, $d, $g]);
    
    $c->flatten();
    

    Will output:

    Illuminate\Support\Collection {#3124
        all: [
            "a",
            "b",
            "c",
            "d",
            "e",
            "f",
            "g",
            "h",
            "i",
        ],
    }