10

php 数组遍历求大神给解

```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)
)

<无标签>

cnscorpion

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

6 取成 6,6

--- 共有 5 条评论 ---
cnscorpion回复 @开源政治 : 我遍历一下午，脑袋大 3年前
cnscorpion回复 @开源政治 : 大侠你遍历一下呗，看看能出来不 3年前

cnscorpion回复 @开源政治 : 对，先排序以后呢？怎么判断后面一个数是不是最后一个？这点我卡壳了！或者单独的如何判断 3年前

\$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)
) ;

\$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);

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

\$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);

\$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 ) )
\$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);

#### 引用来自“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);