如何使用自定义键mapWithKeys返回数组?

时间:2017-10-11 21:01:01

标签: laravel laravel-5.3 laravel-5.4 laravel-5.5 laravel-collection

这是在Laravel中迭代集合的代码:

$usersData = $users->mapWithKeys(function ($item) {
    return [$item->id => array("name" => $item->name, "email" => $item->email, "id" => $item->id)];
 });

我尝试使用自定义$usersData获取数组key,并将值作为数组。

但结果我得到了这个:

array:1 [  0 => array:3 [    "name" => "Doctor"    "email" => "doctor@il.com"    "id" => 2  ]]

而是键2我有数组元素的键0

1 个答案:

答案 0 :(得分:3)

我相信你做错了什么。看看这个:

$users = collect([
    (object)['id' => 5, 'value' => 30, 'something' => 'else'],
    (object)['id' => 6, 'value' => 40, 'something' => 'else2'],
    (object)['id' => 7, 'value' => 50, 'something' => 'else3'],
    (object)['id' => 8, 'value' => 60, 'something' => 'else4'],
    (object)['id' => 9, 'value' => 70, 'something' => 'else5'],
    (object)['id' => 30, 'value' => 90, 'something' => 'else6'],
]);

$users = $users->mapWithKeys(function($user, $key) {
    return [$user->id => $user];
});

dd($users);

结果如下:

Collection {#374
  #items: array:6 [
    5 => {#364
      +"id": 5
      +"value": 30
      +"something": "else"
    }
    6 => {#363
      +"id": 6
      +"value": 40
      +"something": "else2"
    }
    7 => {#362
      +"id": 7
      +"value": 50
      +"something": "else3"
    }
    8 => {#361
      +"id": 8
      +"value": 60
      +"something": "else4"
    }
    9 => {#356
      +"id": 9
      +"value": 70
      +"something": "else5"
    }
    30 => {#357
      +"id": 30
      +"value": 90
      +"something": "else6"
    }
  ]
}

完全符合预期。您确定不会使用例如dd($users->values())显示结果吗?因为values()将删除这些键,在这种情况下,您将获得从0到5的索引。

你的情况不起作用,试试这个 - 这应该有用,应该让你知道你做错了什么。