Laravel chunk on collection return first element as arrays and second as object

Car*_*zar 2 php laravel eloquent

I get all the records from a model, but i need to take chunks from it, i only need the values of the email so i map it

$forwadings = \App\Models\ForwardingEmail::where('company_id', $companyId)
->where('status', 1)
->get(['email']);
->map(function($forwarding) {
    return $forwarding['email'];
})
return $forwadings;
Run Code Online (Sandbox Code Playgroud)

the return display this

[
  "email12@example.com",
  "email13@example.com",
  "email1@example.com",
  "email2@example.com",
  "email3@example.com",
  "email6@example.com",
  "email7@example.com",
  "email8@example.com",
  "email4@example.com",
  "email5@example.com",
  "email9@example.com",
  "email10@example.com"
]
Run Code Online (Sandbox Code Playgroud)

the problem here is when i do return $forwardings->chunk(10), it show this:

[
  [
    "email12@example.com",
    "email13@example.com",
    "email1@example.com",
    "email2@example.com",
    "email3@example.com",
    "email6@example.com",
    "email7@example.com",
    "email8@example.com",
    "email4@example.com",
    "email5@example.com"
  ],
  {
    "10": "email9@example.com",
    "11": "email10@example.com"
  }
]
Run Code Online (Sandbox Code Playgroud)

why this happens? and how can i solve this? i tried using toArray on the chunk result but did not work. i am using laravel 5.3

aim*_*mme 7

我知道现在有点晚了,但它已经有了答案。当我正在寻找一种在使用块方法时重置每个块的键的方法时,我遇到了这个问题。就我而言,我的模型也加载了关系,因此对我来说,将实体保留为对象而不是数组很重要。但array_values对我不起作用,相反,集合的values方法对我有用。分享这个答案只是为了帮助那些访问此页面的人按照我到达这里的方式寻找答案。

这是对我有用的适用于这个问题的方法。

$chunks = \App\Models\ForwardingEmail::where('company_id', $companyId)
    ->where('status', 1)
    ->pluck('email')
    ->chunk(10);

$chunks = $chunks->map(function($chunk) {
   return $chunk = $chunk->values();
});

return $chunks;
Run Code Online (Sandbox Code Playgroud)


mat*_*ard 5

Laravel的->chunk()方法将增量id应用于所有分块项目。当转换为JSON时,这是一个问题,因为JavaScript不允许数组以偏移键值开头(而不是以0开头),因此必须将它们定义为对象。

您可以自行处理以删除键值。这样的事情应该起作用。

$chunks = \App\Models\ForwardingEmail::where('company_id', $companyId)
    ->where('status', 1)
    ->pluck('email')
    ->chunk(10);

foreach ($chunks as $key => $chunk) {
    $chunks[$key] = array_values($chunk->toArray());
}

return $chunks;
Run Code Online (Sandbox Code Playgroud)