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

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

WBOY
Release: 2016-06-13 12:19:25
Original
931 people have browsed it

求大神解决下php数组循环的问题
我有一个数组如下

$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个一分组 
而且每组要重复两次
------解决思路----------------------

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

------解决思路----------------------
<br />$arr = array(1,2,3,4,5,6,7,8);<br />$n = 2; // 循环2次<br />$split = 4; // 4个为一个分组<br />echo '<pre class="brush:php;toolbar:false">';<br />response($arr, $n, $split);<br />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";
}
}


<br />start1<br />1<br />2<br />3<br />4<br />end1<br />start2<br />1<br />2<br />3<br />4<br />end2<br />----------------------------------------------------------<br />start1<br />5<br />6<br />7<br />8<br />end1<br />start2<br />5<br />6<br />7<br />8<br />end2<br />
Copy after login

Related labels:
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