Search code examples
phplaravellaravel-collection

Transform laravel collection


I need a certain array format like this:

    $data = [
        1 => ['order' => 3],
        2 => ['order' => 2],
        3 => ['order' => 1]
    ];

So when I do:

    $ids = $items->transform(function ($item) {
        return [$item->id => ['order' => rand(1,10)]];
    })->all();

Gives:

array:3 [
  0 => array:1 [
    1 => array:1 [
      "order" => 8
    ]
  ]
  1 => array:1 [
    2 => array:1 [
      "order" => 3
    ]
  ]
  2 => array:1 [
    3 => array:1 [
      "order" => 10
    ]
  ]
]

How can I transform the array in a specific way I need above? TIA


Solution

  • you can use mapWithKeys, docs is here: https://laravel.com/docs/5.5/collections#method-mapwithkeys

    $keyed = $items->mapWithKeys(function ($item) {
        return [$item->id => ['order' => rand(1,10)]];
    });
    
    $ids = $keyed->all();