Wednesday, March 8, 2017

Laravel 5: How to put multiple items into the same key in a collection without overriding?

Trying to figure out how to parse a collection and put multiple items into the same key in another collection.

Currently I'm doing this using an array and then I make a collection out of it, but the items inside are not of type Collection, each key is an array and I can't use methods like first() on those arrays. Yes, I can use [0] instead, but I'd prefer to have access to methods available for collections.

$some_array = [];

// Parsing the existing collection using foreach
foreach ($items_collection as $item) {
    // Doing some checks
    if ($item->some_attribute1 == 1
        && @$item->some_relation->some_attribute2
    ) {
        // Putting the item into the array with a specific dynamic key
        $some_array[$item->some_relation->some_attribute2][] = $item->some_relation;
    }
    else if ($item->some_attribute1 == 0
        && @$item->some_relation->some_attribute3) {
        // Putting the item into the array with a specific dynamic key
        $some_array[$item->some_relation->some_attribute3][] = $item->some_relation;
    }
}

// Defining a new Collection
$new_collection = new Collection();

// Parsing the array of groups of items and putting them in the newly created Collection by their key
foreach ($some_array as $key => $key_items) {
    $new_collection->put($key, $key_items);
}

If to make something like this

$some_collection = new Collection();

foreach ($items_collection as $item) {
    if ($item->some_attribute1 == 1
        && @$item->some_relation->some_attribute2
    ) {
        $some_collection->put($item->some_relation->some_attribute2, $item->some_relation);
    }
    else if ($item->some_attribute1 == 0
        && @$item->some_relation->some_attribute3) {
        $some_collection->put($item->some_relation->some_attribute3, $item->some_relation);
    }
}

then instead of storing all the items in the same key the new items will just override the old ones. Is there a way to put multiple items in the same key using put()?

Thank you in advance!



via Eseth

Advertisement