lethalMango
lethalMango

Reputation: 4491

(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

Upvotes: 0

Views: 179

Answers (3)

Dejan Marjanović
Dejan Marjanović

Reputation: 19380

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

Upvotes: 1

mario
mario

Reputation: 145482

There is a built-in function for that:

$parts = array_chunk($array, 23);

Upvotes: 7

jensgram
jensgram

Reputation: 31508

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

Upvotes: 1

Related Questions