Maison >développement back-end >tutoriel php >php 算法之如何打印出下图
自己偶尔看到了下图,于是用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 ";}
方法二:如代码,先给出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>";}