改变laravel集合

改变laravel集合

问题描述:

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

我需要这样的数组格式: p>

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

所以当我这样做时: p>

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

给出: p>

  array:3 [
 0 => 数组:1 [
 1 => 数组:1 [
“order”=>  8 
] 
] 
 1 => 数组:1 [
 2 => 数组:1 [
“order”=>  3 
] 
] 
 2 => 数组:1 [
 3 => 数组:1 [
“order”=>  10 
] 
] 
] 
  code>  pre> 
 
 

如何以上面我需要的特定方式转换数组? TIA p> div>

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();