Slice an array into 4 other arrays

南笙酒味 提交于 2019-12-02 10:04:30

问题


I have an array which I want to slice in 4 other arrays because I want to display the content of the first array on four columns.

I have tried the code above, but what I get is N columns with 4 items.

$groups = array();
for ($i = 0; $i < count($menu); $i += 4) $groups[] = array_slice($menu, $i, 4);

Can this be modified in order to get exactly 4 columns and distribute the values so they fit?


回答1:


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));



回答2:


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));
}


来源:https://stackoverflow.com/questions/12876333/slice-an-array-into-4-other-arrays

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!