3

我需要这样的某种数组格式:

    $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

4

1 回答 1

7

您可以使用 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();
于 2017-09-29T04:07:26.600 回答