Home > Backend Development > PHP Tutorial > 求大神解决下php数组循环的问题

求大神解决下php数组循环的问题

WBOY
Release: 2016-06-23 13:35:06
Original
871 people have browsed it

我有一个数组如下

$arr = array(1,2,3,4,5,6,7,8);
希望用循环输出
start1
1
2
3
4
end1
start2
1
2
3
4
end2
----------------------------------------------------------
start1
5
6
7
8
end1
start2
5
6
7
8
end2

意思就是把数组 每4个一分组 
而且每组要重复两次


回复讨论(解决方案)

<?php$arr = array(1,2,3,4,5,6,7,8);for($i=0; $i<count($arr); $i+=4){	$temp = array_slice($arr, $i, 4);	for($k=1; $k<=2; $k++){		echo 'start'.$k.'<br>';		foreach ($temp as $val) {			echo $val.'<br>';		}		echo 'end'.$k.'<br>';	}}
Copy after login

$arr = array(1,2,3,4,5,6,7,8);$n = 2; // 循环2次$split = 4; // 4个为一个分组echo '<pre class="brush:php;toolbar:false">';response($arr, $n, $split);echo '
Copy after login
';function response($arr, $n, $split){ while(count($arr)>0){ $tmp = array_splice($arr, 0, $split); for($i=0;$i<$n;$i++){ echo 'start'.($i+1)."\r\n"; echo implode("\r\n", $tmp)."\r\n"; echo 'end'.($i+1)."\r\n"; } echo "----------------------------------------------------------\r\n"; }}

start11234end1start21234end2----------------------------------------------------------start15678end1start25678end2
Copy after login

while(count($arr)>0)
while循环没有终止 为什么是正常的呢

while(count($arr)>0)
while循环没有终止 为什么是正常的呢



array_splice 会把 $arr的元素拿出,使$arr元素减少。所以当元素全部取出后。$arr为空,退出循环。

好的 非常感谢

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template