自己偶尔看到了下图。于是用php打印出下图。
两种方法解决此问题:
方法一:依据图分析该图是一个二维数组,可用二维数组解决此类问题,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 "<br/>"; }
方法二:如代码。先给出size个空数组。在空数组中填充元素。
详细方法例如以下:
<?php function array_chunk_vertical($input, $size, $preserve_keys = FALSE, $size_is_horizontal = false) { $chunks = array(); if ($size_is_horizontal) { $chunk_count = ceil(count($input) / $size); } else { $chunk_count = $size; } for ($chunk_index = 0; $chunk_index < $chunk_count; $chunk_index++) { $chunks[] = array(); } $chunk_index = 0; foreach ($input as $key => $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 "<br/>"; }
原文:http://www.cnblogs.com/lxjshuju/p/7222897.html