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

OPV*_*OPV 1 laravel laravel-collection laravel-5.3 laravel-5.4 laravel-5.5

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

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

我试图获得$usersData具有自定义key和值作为数组的数组。

但是结果我得到了:

array:1 [  0 => array:3 [    "name" => "Doctor"    "email" => "doctor@il.com"    "id" => 2  ]]
Run Code Online (Sandbox Code Playgroud)

相反,键2我有0数组元素的键。

Mar*_*łek 5

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

$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);
Run Code Online (Sandbox Code Playgroud)

结果是:

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"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

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

如果您的案例不起作用,请尝试使用此方法-这应该起作用,并且应该让您知道您在做什么错。