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

How to return array with custom key mapWithKeys?

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

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

我尝试使用自定义 key 和值作为数组来获取数组 $usersData

但我得到的结果是:

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

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

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

$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 的索引。

如果你的情况不适用,试试这个 - 这应该可以,并且应该让你知道你做错了什么。