我有一个对象数组,每个对象都有一个唯一的随机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个一组的块,以便进行分页。
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的原始数组键?
3条答案
按热度按时间8i9zcol21#
我所要做的就是将
array_chunk()
的第三个参数设置为true,如下所示:j2datikz2#
看起来array array_chunk ( array $input , int $size [, bool $preserve_keys = false ] )的第三个参数正好控制了这一点。
印刷品
vbkedwbf3#
如果您想要相同但保留原始数字键:
结果:
在静态Helper函数中: