当前位置:Gxlcms > PHP教程 > php怎么将一个二维数组拆分成几个数组

php怎么将一个二维数组拆分成几个数组

时间:2021-07-01 10:21:17 帮助过:23人阅读

怎么将下面二维数组拆分成几个数组

$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个不一定

$arrnew[0] = array(

array(
'id' => 1,
'user_name'=>'test1'
),
array(
'id' => 2,
'user_name'=>'test2'
)

);
$arrnew[1] = array(

array(
'id' => 3,
'user_name'=>'test3'
),,
array(
'id' => 4,
'user_name'=>'test2'
)

);
$arrnew[2] = array(
array(

'id' => 5,
'user_name'=>'test3'
)

);

回复内容:

怎么将下面二维数组拆分成几个数组

$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个不一定

$arrnew[0] = array(

array(
'id' => 1,
'user_name'=>'test1'
),
array(
'id' => 2,
'user_name'=>'test2'
)

);
$arrnew[1] = array(

array(
'id' => 3,
'user_name'=>'test3'
),,
array(
'id' => 4,
'user_name'=>'test2'
)

);
$arrnew[2] = array(
array(

'id' => 5,
'user_name'=>'test3'
)

);

array_chunk($arr,$num);//$num为2或3

试下下面逻辑是否正确

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

人气教程排行