Home > Mobile >  Change collection index
Change collection index

Time:05-13

This is Laravel collection question. I make a standard query to the database and get a collection. So far no problem.

Here result:

"id" => 1
"Certificate" => "001"
"Name" => "BTYUUU"
"Code" => "58X-AAAA-1G"

"id" => 2
"Certificate" => "002"
"Name" => "BTYSSS"
"Code" => "58X-SSS-1G" 

But I want different arrange of result like this:

    [58X-AAAA-1G] => Array
        (
            [id] => 1
            [Certificate] => 001
            [Name] => BTYUUU
            [Code] => 58X-AAAA-1G
        )
        
    [58X-SSS-1G] => Array
        (
            [id] => 2
            [Certificate] => 002
            [Name] => BTYSSS
            [Code] => 58X-SSS-1G
        ) 

This is just draft. May be list in object is. Thanks for the help or advice

CodePudding user response:

You can use ->keyBy('Code'); on the collection.

https://laravel.com/docs/9.x/collections#method-keyby

CodePudding user response:

keyBy()

The keyBy method keys the collection by the given key. If multiple items have the same key, only the last one will appear in the new collection:

$collection = collect([
    ['product_id' => 'prod-100', 'name' => 'Desk'],
    ['product_id' => 'prod-200', 'name' => 'Chair'],
]);
 
$keyed = $collection->keyBy('product_id');
 
$keyed->all();
 
/*
    [
        'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
        'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
    ]
*/
  • Related