以下是我要拆分的示例数组:
(1,2,3,4,5,0,6,7,0,8,9,10,11,12,0)
如何将其拆分为3个这样的数组?
(1,2,3,4,5,0) (6,7,0) (8,9,10,11,12,0)
答案 0 :(得分:1)
这是解决方案。 (作者说他希望分成'0'而不是重复值)
function split_array_by_duplicate_values($a, $duplicate = 0)
{
$c = array_intersect($a, array($duplicate));
$r = array();
$i = 0;
foreach($c as $k => $v) {
$l = ++$k - $i;
$r[] = array_slice($a, $i, $l);
$i = $k;
}
return $r;
}
$a = array(1,2,3,4,5,0,6,7,0,8,9,10,11,12,0);
print_r(split_array_by_duplicate_values($a));
返回
Array
(
[0] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 0
)
[1] => Array
(
[0] => 6
[1] => 7
[2] => 0
)
[2] => Array
(
[0] => 8
[1] => 9
[2] => 10
[3] => 11
[4] => 12
[5] => 0
)
)
答案 1 :(得分:0)
试试这个:
$array = array(1, 2, 3, 0, 4, 5, 6);
$array_0 = array_splice($array, 0, 4);
$array_1 = array_splice($array, 4);
答案 2 :(得分:0)
我认为你要找的是array_splice
。
$array=array(1,2,3,0,4,5,6);
$newarray=array_splice($array,4);
print_r($array); //Array ( [0] => 1 [1] => 2 [2] => 3 [3]=>0);
print_r($newarray); //Array( [0]=>4 [1]=>5 [2]=>6)
如果要将数组拆分为一个多维数组中的两个数组,可以执行
$array=array(1,2,3,0,4,5,6);
$newarray=array_chunk($array,4); //returns [[1,2,3,0],[4,5,6]]
答案 3 :(得分:0)
您应该使用数组拆分来按需要拆分数组
<?php
$input = array("a", "b", "c", "d", "e");
$output = array_slice($input, 2); // returns "c", "d", and "e"
$output = array_slice($input, -2, 1); // returns "d"
$output = array_slice($input, 0, 3); // returns "a", "b", and "c"
// note the differences in the array keys
print_r(array_slice($input, 2, -1));
print_r(array_slice($input, 2, -1, true));
?>