Praveen Kumar
Praveen Kumar

Reputation: 89

Splitting one Array into many Array in PHP

I'm in need of splitting of the single array into multiple array for some report generating purpose.

I have an array like this which I have given below.

Array
(
    [blah_1] => 1
    [blahblah_1] => 31
    [blahblahblah_1] => 25
    [blah_3] => 1
    [blahblah_3] => 3
    [blahblahblah_3] => 5
    [blah_10] => 1
    [blahblah_10] => 10
    [blahblahblah_10] => 2
)

I want to split the above to,

Array
(
    [blah_1] => 1
    [blahblah_1] => 31
    [blahblahblah_1] => 25
)

Array
(
    [blah_3] => 1
    [blahblah_3] => 3
    [blahblahblah_3] => 5
)

Array
(
    [blah_10] => 1
    [blahblah_10] => 10
    [blahblahblah_10] => 2
)

How can I do this in PHP ??

Upvotes: 0

Views: 367

Answers (5)

Death
Death

Reputation: 2017

$oldarray=array('blah_1'=>1,'blahblah_1'=>31,'blahblahblah_1'=>25,
'blah_3'=>1,'blahblah_3'=>3,'blahblahblah_3'=>5,
'blah_10'=>1,'blahblah_10'=>10,'blahblahblah_10'=>2
)
$newarray=array();

foreach ($oldarray as $key=>$val) { //Loops through each element in your original array

    $parts=array_reverse(explode('_',$key)); //Splits the key around _ and reverses
    $newarray[$parts[0]][$key]=$val; //Gets the first part (the number) and adds the
    //value to a new array based on this number.

}

The output will be:

Array (
    [1]=>Array
    (
        [blah_1] => 1
        [blahblah_1] => 31
        [blahblahblah_1] => 25
    )

    [3]=>Array
    (
        [blah_3] => 1
        [blahblah_3] => 3
        [blahblahblah_3] => 5
    )

    [10]=>Array
    (
        [blah_10] => 1
        [blahblah_10] => 10
        [blahblahblah_10] => 2
    )
)

Upvotes: 2

Macsen Liviu
Macsen Liviu

Reputation: 90

Not sure if you are looking for array_slice

but take a look at this example:

    <?php
        $input = array("a", "b", "c", "d", "e");


       print_r(array_slice($input, 2, -1));
       print_r(array_slice($input, 2, -1, true));
?>

will result in this:

Array
(
    [0] => c
    [1] => d
)
Array
(
    [2] => c
    [3] => d
)

Upvotes: 0

Ruben Nagoga
Ruben Nagoga

Reputation: 2218

Use array_chunk

i.e

$a = array(1,2,3,4,5,6,7);
var_dump(array_chunk($a, 3));

Upvotes: 0

tildy
tildy

Reputation: 1009

array_chunk ( array $input , int $size);

Upvotes: -1

Ignas
Ignas

Reputation: 1965

Use array_chunk. Example:

<?php
   $chunks = array_chunk($yourarray, 3);
   print_r($chunks);
?>

Upvotes: 0

Related Questions