Home >Backend Development >PHP Tutorial >How to split a two-dimensional array into several arrays in php
How to split the following two-dimensional array into several arrays
<code>$arr = array( array( 'id' => 1, 'user_name'=>'test1' ), array( 'id' => 2, 'user_name'=>'test2' ), array( 'id' => 3, 'user_name'=>'test3' ),, array( 'id' => 4, 'user_name'=>'test2' ), array( 'id' => 5, 'user_name'=>'test3' ) ); 拆分后,个数不一定,每组2个或者3个不一定</code>
$arrnew[0] = array(
<code>array( 'id' => 1, 'user_name'=>'test1' ), array( 'id' => 2, 'user_name'=>'test2' )</code>
);
$arrnew[1] = array(
<code>array( 'id' => 3, 'user_name'=>'test3' ),, array( 'id' => 4, 'user_name'=>'test2' )</code>
);
$arrnew[2] = array(
array(
<code>'id' => 5, 'user_name'=>'test3' )</code>
);
How to split the following two-dimensional array into several arrays
<code>$arr = array( array( 'id' => 1, 'user_name'=>'test1' ), array( 'id' => 2, 'user_name'=>'test2' ), array( 'id' => 3, 'user_name'=>'test3' ),, array( 'id' => 4, 'user_name'=>'test2' ), array( 'id' => 5, 'user_name'=>'test3' ) ); 拆分后,个数不一定,每组2个或者3个不一定</code>
$arrnew[0] = array(
<code>array( 'id' => 1, 'user_name'=>'test1' ), array( 'id' => 2, 'user_name'=>'test2' )</code>
);
$arrnew[1] = array(
<code>array( 'id' => 3, 'user_name'=>'test3' ),, array( 'id' => 4, 'user_name'=>'test2' )</code>
);
$arrnew[2] = array(
array(
<code>'id' => 5, 'user_name'=>'test3' )</code>
);
array_chunk($arr,$num);//$num is 2 or 3
Try whether the following logic is correct
<code> $arr = array( array( 'id' => 1, 'user_name'=>'test1' ), array( 'id' => 2, 'user_name'=>'test2' ), array( 'id' => 3, 'user_name'=>'test3' ), array( 'id' => 4, 'user_name'=>'test2' ), array( 'id' => 5, 'user_name'=>'test3' ) ); rsort($arr); $newArr = []; while(!empty($arr)) { $count = rand(2,3);/这里控制一个数组要几个元素,此处设置2-3个 $tmpArr = []; for($i = 0; $i< $count ; $i++) { $tmpArr[] = array_pop($arr); } $newArr[] = $tmpArr; } dump($newArr);</code>