gpt4 book ai didi

php - 如何在使用 array_chunk 时保留原始的唯一数组键?

转载 作者:可可西里 更新时间:2023-11-01 12:23:19 24 4
gpt4 key购买 nike

我有一个对象数组,每个对象都有一个唯一的随机 ID。

111 => 
object(stdClass)[452]
public 'Description' => string 'Description here...' (length=728)
public 'Name' => string 'Shirt' (length=18)
public 'Price' => float 36.56

222 =>
object(stdClass)[452]
public 'Description' => string 'Description here...' (length=728)
public 'Name' => string 'Pants' (length=18)
public 'Price' => float 36.56

333 =>
object(stdClass)[452]
public 'Description' => string 'Description here...' (length=728)
public 'Name' => string 'Dress' (length=18)
public 'Price' => float 36.56

444 =>
object(stdClass)[452]
public 'Description' => string 'Description here...' (length=728)
public 'Name' => string 'Dress' (length=18)
public 'Price' => float 36.56

...

我的目标是将我的键控对象数组拆分为 2 个 block ,以便进行分页。所以像这样的事情会做:

0 =>
111 =>
object(stdClass)[452]
public 'Description' => string 'Description here...' (length=728)
public 'Name' => string 'Shirt' (length=18)
public 'Price' => float 36.56

222 =>
object(stdClass)[452]
public 'Description' => string 'Description here...' (length=728)
public 'Name' => string 'Pants' (length=18)
public 'Price' => float 36.56
1 =>
333 =>
object(stdClass)[452]
public 'Description' => string 'Description here...' (length=728)
public 'Name' => string 'Dress' (length=18)
public 'Price' => float 36.56

444 =>
object(stdClass)[452]
public 'Description' => string 'Description here...' (length=728)
public 'Name' => string 'Dress' (length=18)
public 'Price' => float 36.56
...

我的问题是通过使用 array_chunk() 将我的对象数组分成 2 组,我的唯一 ID 没有被保留。

private function paginate($array)
{
$chunks = 2;
$paginatedResults = array_chunk($array, $chunks);

return $paginatedResults;
}

函数输出:

0 =>
0 =>
object(stdClass)[452]
public 'Description' => string 'Description here...' (length=728)
public 'Name' => string 'Shirt' (length=18)
public 'Price' => float 36.56

1 =>
object(stdClass)[452]
public 'Description' => string 'Description here...' (length=728)
public 'Name' => string 'Pants' (length=18)
public 'Price' => float 36.56
1 =>
0 =>
object(stdClass)[452]
public 'Description' => string 'Description here...' (length=728)
public 'Name' => string 'Dress' (length=18)
public 'Price' => float 36.56

1 =>
object(stdClass)[452]
public 'Description' => string 'Description here...' (length=728)
public 'Name' => string 'Dress' (length=18)
public 'Price' => float 36.56
...

如何将我的键控对象数组拆分为另一个包含每个索引 2 个对象的数组,同时保留包含唯一 ID 的原始数组键?

最佳答案

我所要做的就是将 array_chunk() 的第三个参数设置为 true,如下所示:

$paginatedResults = array_chunk($array, $chunk, true);

关于php - 如何在使用 array_chunk 时保留原始的唯一数组键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27276206/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com