改变laravel集合

时间:2017-09-29 03:57:07

标签: php laravel 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

1 个答案:

答案 0 :(得分:3)

你可以使用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();