变换 laravel 集合

Transform laravel collection

我需要这样的特定数组格式:

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

所以当我这样做时:

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

给出:

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
    ]
  ]
]

如何以我需要的特定方式转换数组? TIA

你可以使用 mapWithKeys,文档在这里:https://laravel.com/docs/5.5/collections#method-mapwithkeys

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

$ids = $keyed->all();