Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 646
jsdecena Avatar asked Oct 14 '25 15:10

jsdecena


1 Answers

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();
like image 184
Hanlin Wang Avatar answered Oct 17 '25 05:10

Hanlin Wang