开发者

(PHP) Separating Arrays into Multidimensional

At present I have an array of data [0] - [574].

What I would like to do is split this down into a multidimensional array in 25 parts i.e. [0] - [22] as below:

Array
(
    [0开发者_运维知识库] =>
        [0] => abc
        ...
        [22] => xyz
    [1] =>
        [0] => abc
        ...
        [22] => xyz
    ...
}

I assume it can be done using a for loop to split it all up - Ive tried a few methods but havent seemed to quite get there yet!

Thanks

-mango


There is a built-in function for that:

$parts = array_chunk($array, 23);


I've just used dummy data, but you'll get the idea:

// Set up input with dummy data
$input = array();
for ($i = 0; $i < 574; $i++) {
        $input[] = $i . 'aaa';
}

$out = array();
for ($i = 0, $j = sizeof($input); $i < $j; $i++) {
        $bucket = floor($i / ($j / 25));
        if (!isset($out[$bucket])) {
                $out[$bucket] = array();
        }
        $out[$bucket][] = $input[$i];
}

print_r($out);


$array = array();
$chunks = ceil(count($array) / 25);
$new = array_chunk($array, $chunks);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜