Slice an array into 4 other arrays

有些话、适合烂在心里 提交于 2019-12-02 03:15:39

Like Michael Berkowski suggested:

$groups = array_chunk($menu,4);

Should give you what you need. If you're more into "manual labour":

$groups = array();
while($groups[] = array_splice($menu,0,4))
{//no need for any code here ^^ chunks the array just fine
    printf('This loop will run another %d times<br/>',(int)ceil(count($menu)/4));
}

Update:

I see I got this a bit wrong... want to chunk into 4 arrays, not into arrays of four:

$groups = array_chunk($menu,(int)ceil(count($menu)/4));

You can try

// Some Random array
$array = range(1, 20);

// Split it 4 Chuncks
$array = array_chunk($array, 4);

// Slice The first 4 Chunks
$array = array_slice($array, 0, 4);

// Output Result
foreach ( $array as $set ) {
    printf("<li>%s</li>", implode(",", $set));
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!