时间:2021-07-01 10:21:17 帮助过:20人阅读
两种方法解决此问题:
方法一:根据图分析该图是一个二维数组,可用二维数组解决此类问题,6行就是6个数组,每一行就代表数组有多少个元素。知道每个数组元素的个数,不就可以知道数组中有哪几个元素吗?
function array_chunk_vertical($arr, $colun){ $arr_length = count($arr); $parem = floor($arr_length / $colun); $pare = $arr_length % $colun; $ar = array(); for ($i = 0; $i < $colun; $i ++) { $par = $i == $colun - 1 ? 1 : 5; $ar[] = $par; } $newarray = array(); foreach ($ar as $value) { for ($i = 0; $i < $value; $i ++) { $newarray[$i][] = array_shift($arr); } } return $newarray;}$arr = range(1, 31);$data = array_chunk_vertical($arr, 7);foreach ($data as $value) { foreach ($value as $va) { printf('[%2s]', $va); } echo "
";}
方法二:如代码,先给出size个空数组,在空数组中填充元素。具体方法如下:
$value) { if ($preserve_keys) { $chunks[$chunk_index][$key] = $value; } else { $chunks[$chunk_index][] = $value; } if (++$chunk_index == $chunk_count) { $chunk_index = 0; } } return $chunks;}$data=range(1,31);$newdata=array_chunk_vertical($data,6);foreach ($newdata as $root){ foreach ($root as $val){ printf('[%2s]',$val); } echo "
";}