## php 数组遍历求大神给解

cnscorpion 发布于 2015/07/07 19:19

```array(21,1,2,5,7,8,50,68,69,70,71,72)

array(
array(21,21),
array(1,2),
array(5,5),
array(7,8),
array(50,50),
array(68,72)
)

0

0

#### 引用来自“开源政治”的评论

6 取成 6,6

0

0

1,2 就取 1,2

0

\$arr = array(21,1,2,5,7,8,50,68,69,70,71,72); 一维数组

\$new_array =array(
array(21,21),
array(1,2),
array(5,5),
array(7,8),
array(50,50),
array(68,72)
) ;

0
\$arr = array(21,1,2,5,7,8,50,68,69,70,71,72);
\$new_arr = array();
sort(\$arr);
\$a = \$b = array_shift(\$arr);
foreach(\$arr as \$value){
if(\$b+1 == \$value){
\$b = \$value;
}else{
\$new_arr[] = array(\$a,\$b);
\$a = \$b = \$value;
}
}
\$new_arr[] = array(\$a,\$b);
var_dump(\$new_arr);
0

#### 引用来自“开源政治”的评论

\$arr = array(21,1,2,5,7,8,50,68,69,70,71,72);
\$new_arr = array();
sort(\$arr);
\$a = \$b = array_shift(\$arr);
foreach(\$arr as \$value){
if(\$b+1 == \$value){
\$b = \$value;
}else{
\$new_arr[] = array(\$a,\$b);
\$a = \$b = \$value;
}
}
\$new_arr[] = array(\$a,\$b);
var_dump(\$new_arr);

0
\$arr1 = array(21,1,2,5,7,8,50,68,69,70,71,72); \$num = count(\$arr1); \$newArr = array(); for(\$key=0;\$key<\$num;\$key++){ \$v1 = \$arr1[\$key]; if(\$num-1 > \$key){ \$v2 = \$arr1[(\$key+1)]; }else if(isset(\$arr1[\$key]) && !isset(\$arr1[(\$key+1)])){ \$newArr[] = array(\$v1,\$v1); break; }else{ break; } if(\$v1 == (\$v2-1)){ \$newArr[] = array(\$v1,\$v2); \$key++; }else{ \$newArr[] = array(\$v1,\$v1); } } print_r(\$newArr); 结果： Array ( [0] => Array ( [0] => 21 [1] => 21 ) [1] => Array ( [0] => 1 [1] => 2 ) [2] => Array ( [0] => 5 [1] => 5 ) [3] => Array ( [0] => 7 [1] => 8 ) [4] => Array ( [0] => 50 [1] => 50 ) [5] => Array ( [0] => 68 [1] => 69 ) [6] => Array ( [0] => 70 [1] => 71 ) [7] => Array ( [0] => 72 [1] => 72 ) )
0
\$arr1 = array(21,1,2,5,7,8,50,68,69,70,71,72); \$num = count(\$arr1); \$newArr = array(); for(\$key=0;\$key<\$num;\$key++){ \$v1 = \$arr1[\$key]; if(\$num-1 > \$key){ \$v2 = \$arr1[(\$key+1)]; }else if(isset(\$arr1[\$key]) && !isset(\$arr1[(\$key+1)])){ \$newArr[] = array(\$v1,\$v1); break; }else{ break; } if(\$v1 == (\$v2-1)){ \$newArr[] = array(\$v1,\$v2); \$key++; }else{ \$newArr[] = array(\$v1,\$v1); } } print_r(\$newArr);
0

#### 引用来自“suhanyujie”的评论

\$arr1 = array(21,1,2,5,7,8,50,68,69,70,71,72); \$num = count(\$arr1); \$newArr = array(); for(\$key=0;\$key<\$num;\$key++){ \$v1 = \$arr1[\$key]; if(\$num-1 > \$key){ \$v2 = \$arr1[(\$key+1)]; }else if(isset(\$arr1[\$key]) && !isset(\$arr1[(\$key+1)])){ \$newArr[] = array(\$v1,\$v1); break; }else{ break; } if(\$v1 == (\$v2-1)){ \$newArr[] = array(\$v1,\$v2); \$key++; }else{ \$newArr[] = array(\$v1,\$v1); } } print_r(\$newArr);