在输入中创建数组:
Array
(
[0] => 10
[1] => -1
[2] => -1
[3] => -1
[4] => -1
[5] => 15
[6] => 16
[7] => 17
[8] => -1
[9] => -1
[10] => 20
)
我如何将它拆分为-1值,输出为:
Array
(
[0] => 10
[1] => Array
(
[0] => 15
[1] => 16
[2] => 17
)
[2] => Array
(
[0] => 20
)
)
php explode()
函数适用于字符串输入。虽然这是阵列的东西。
答案 0 :(得分:1)
1 <?php
2 $array = [10, -1, -1, -1, -1, 15, 16, 17, -1, -1, 20];
3 $tempArray = [];
4 $result = [];
5 foreach($array as $item)
6 {
7 if($item == -1)
8 {
9 if(count($tempArray))
10 {
11 $result[] = $tempArray;
12 $tempArray = [];
13 }
14 }
15 else
16 $tempArray[] = $item;
17
18 }
19 if(count($tempArray))
20 {
21 $result[] = $tempArray;
22 }
23 echo json_encode($result);
结果是,
~$ php cal.php
[[10],[15,16,17],[20]]
答案 1 :(得分:1)
这里有解决方案。
* {padding:0; margin:0;}
输出:
$myAry = array(
'0' => 10,
'1' => -1,
'2' => -1,
'3' => -1,
'4' => -1,
'5' => 15,
'6' => 16,
'7' => 17,
'8' => -1,
'9' => -1,
'10' => 20
);
$newAry = Array();
function splitArray($ary , $index){
global $newAry;
if($index == count($ary)){
return $newAry;
}
if( $ary[$index] != -1 ){
$chunk = array();
while( $index < count($ary) && $ary[$index] != -1 ){
array_push($chunk , $ary[$index]);
$index++;
}
array_push($newAry , $chunk);
splitArray($ary , $index);
} else {
$index++;
splitArray($ary , $index);
}
}
splitArray($myAry , 0);
print_r($newAry);
答案 2 :(得分:0)
使用array_unique
和unset
$array = array_unique($array);
foreach ($array as $k=>$item) {
if($item == '-1'){
unset($array[$k]);
}
}
输出
array(5) {
[0]=>
int(10)
[5]=>
int(15)
[6]=>
int(16)
[7]=>
int(17)
[10]=>
int(20)
}