我有一个数组:
Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => 4
[5] => 5
[6] => 6
[7] => 7
[8] => 8
[9] => 9
)
我想将数组拆分为大小为2,然后是3然后是2然后是3等的块:
Array
(
[0] => Array
(
[0] => 0
[1] => 1
[2] => 2
)
[1] => Array
(
[0] => 3
[1] => 4
)
[2] => Array
(
[0] => 5
[1] => 6
[2] => 7
)
[3] => Array
(
[0] => 8
[1] => 9
)
)
到目前为止我什么都没有,想不到一个简单的方法可以做到这一点!感谢。
答案 0 :(得分:5)
这应该有效:
$a = array(0 => 0,1 => 1,2 => 2,3 => 3,4 => 4, 5 => 5, 6 => 6,7 => 7,8 => 8,9 => 9);
$chunks = array();
$i=1;
while(count($a)){
$chunks[] = array_splice($a, 0,(2+($i%2)),array());
$i++;
}
echo "<pre>";
var_dump($chunks);
答案 1 :(得分:2)
您可以使用array_splice
分割数组,但是您需要设置条件吗?你想在什么基础上分裂它们?
您可以使用array_merge
将它们带回array
数组。
如果您当前的代码,代码将是:
<?php
$array = array(0,1,2,3,4,5,6,7,8,9);
$final = array(
array_splice($array, 0, 3),
array_splice($array, 1, 2),
array_splice($array, 1, 2),
array_splice($array, 1, 2),
);
print_r($final);
?>
Array
(
[0] => Array
(
[0] => 0
[1] => 1
[2] => 2
)
[1] => Array
(
[0] => 4
[1] => 5
)
[2] => Array
(
[0] => 6
[1] => 7
)
[3] => Array
(
[0] => 8
[1] => 9
)
)
答案 2 :(得分:0)
试试这个
<?php
$input_array = array('a', 'b', 'c', 'd', 'e');
print_r(array_chunk($input_array, 2));
print_r(array_chunk($input_array, 2, true));
?>
<强>更新强>
<?php
$myArray = array("abc","def","ghi","jkl","mno","pqr","stu","vwx","yz");
$newArray = array_chunk($myArray, 2, false);
// Now process the multidimensional array made from array_chunk()
$i = 0;
foreach ($newArray as $inner_array) {
$i++;
echo "<h2>Chunk $i</h2>";
while (list($key, $value) = each($inner_array)) {
echo "$key: $value <br />";
}
}
?>
<强>输出强>
第1块
0:abc
1:def
第2块
0:ghi
1:jkl
第3块
0:mno
1:pqr
第4块
0:stu
1:vwx
第5块
0:yz
答案 3 :(得分:0)
你可以使用它,它不是最优雅的,但它只是为你做的伎俩 - 你可以很好地修改它并使其适应你的目的进一步:
<?php
$originalArray = array(0,1,2,3,4,5,6,7,8,9);
$counter=count($originalArray);
$isTwo=true;
$newArray=array();
$arrElement=0;
$i=0;
while($i<$counter)
{
if($isTwo)
{
$newArray[$arrElement]= array();
for($j=0; $j<2; $j++)
{
$newArray[$arrElement][$j]=$originalArray[$i+$j];
}
$i+=2;
$isTwo=false;
$arrElement++;
}
else
{
$newArray[$arrElement]= array();
for($j=0; $j<3; $j++)
{
$newArray[$arrElement][$j]=$originalArray[$i+$j];
}
$i+=3;
$isTwo=true;
$arrElement++;
}
}
var_dump($newArray);
?>
输出:
array(4) {
[0]=>
array(2) {
[0]=>
int(0)
[1]=>
int(1)
}
[1]=>
array(3) {
[0]=>
int(2)
[1]=>
int(3)
[2]=>
int(4)
}
[2]=>
array(2) {
[0]=>
int(5)
[1]=>
int(6)
}
[3]=>
array(3) {
[0]=>
int(7)
[1]=>
int(8)
[2]=>
int(9)
}
}
答案 4 :(得分:0)
$tobechunked_arr = array(0,1,2,3,4,5,6,7,8,9);
$chunk_size_arr = array(3,2,3,2);
$j = 0;
foreach($chunk_size_arr as $key => $val)
{
for($i = 0; $i < $val; $i++)
{
$result_arr[$key][] = $tobechunked_arr[$j];
$j++;
}
}
echo "<pre>";
print_r($result_arr);