gpt4 book ai didi

php函数将数组分成3部分而不留下余数

转载 作者:行者123 更新时间:2023-12-02 06:32:16 25 4
gpt4 key购买 nike

我有一个简单的数组,我想将它分成 3 个随机行。

到目前为止,我使用的数组块函数成功地将其拆分为 3 行,但由于数组计数不均匀,它将数组拆分为 3 行,但在 2 行中留下剩余的 4th 值。看下面的代码...

<?php

$my_bikes = array (
'bike-996.png',
'bike-adventure.png',
'bike-bandit.png',
'bike-blade.png',
'bike-classic-racer.png',
'bike-classic-rm.png',
'bike-custom.png',
'bike-dragster.png',
'bike-ducati-scrambler.png',
'bike-electric-concept.png',
'bike-flat-tracker.png',
'bike-goldwing.png',
'bike-gsx.png',
'bike-harley.png',
'bike-indian-vintage.png',
'bike-kiddimoto.png',
'bike-livewire.png',
'bike-lotus.png',
'bike-monkey-bike.png',
'bike-moto3.png',
'bike-mx.png',
'bike-rc.png',
'bike-rc213v.png',
'bike-roland-sands.png',
'bike-scooter.png',
'bike-speedway.png',
'bike-tron.png',
'bike-vespa.png',
'bike-vision.png',
);

shuffle($my_bikes);

// chunk my bike
$my_bikes = array_chunk($my_bikes, count($my_bikes) / 3);

?>

<?php foreach($my_bikes as $key => $my_bike_row) : ?>

<div class="row <?=$key % 2==0 ? 'left' : 'right' ?>">
<?php foreach($my_bike_row as $my_bike): ?>
<img src="<?=get_path('images/bikes/' . $my_bike)?>" alt="">
<?php endforeach; ?>
</div>

<?php endforeach; ?>

<?=exit( '<pre>' . print_r( $my_bikes, true ));?>

在下面查看我当前的输出...
Array
(
[0] => Array
(
[0] => bike-roland-sands.png
[1] => bike-monkey-bike.png
[2] => bike-classic-rm.png
[3] => bike-classic-racer.png
[4] => bike-vespa.png
[5] => bike-rc213v.png
[6] => bike-flat-tracker.png
[7] => bike-dragster.png
[8] => bike-custom.png
)

[1] => Array
(
[0] => bike-speedway.png
[1] => bike-blade.png
[2] => bike-tron.png
[3] => bike-indian-vintage.png
[4] => bike-harley.png
[5] => bike-goldwing.png
[6] => bike-kiddimoto.png
[7] => bike-livewire.png
[8] => bike-moto3.png
)

[2] => Array
(
[0] => bike-adventure.png
[1] => bike-mx.png
[2] => bike-rc.png
[3] => bike-scooter.png
[4] => bike-996.png
[5] => bike-gsx.png
[6] => bike-ducati-scrambler.png
[7] => bike-lotus.png
[8] => bike-electric-concept.png
)

[3] => Array
(
[0] => bike-vision.png
[1] => bike-bandit.png
)

)

如您所见,我只剩下 4 行。

我的问题是,PHP 有什么方法可以将数组拆分为 3 行,但是如果它是奇数(根据我的示例),则最后的余数包含在 3 行中,而不是剩下的。

理想情况下,我不想有任何重复。

谢谢

最佳答案

使用 array_chunk()
并通过 ceil(count($my_bikes)/3) 将分数(如果有)四舍五入到下一个最高整数值来计算大小

所以在这种情况下 - count($my_bikes)/3 => 26/3 => 8.66
ceil(8.66) => 9
块大小将为 9, 9, 8

array_chunk($my_bikes, (ceil(count($my_bikes)/3)))

关于php函数将数组分成3部分而不留下余数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31336428/

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