1

I have an first $array1 of 200 integer values,$array1 integer values are random values and second array say as below

$array2= array('30','40,'70','30','30');

Both the arrays are generating dynamically.

I want to divide my $array1 into smaller arrays as per $array2 values, as first 30 integers from $array1 will make separate array, later 40 intergers from $array1 will make second new array and so on. From above example there will be 5 new arrays.

Can anyone please help me.

I tried below below it can just divide based on values assigned. But it is not useful

$arrays = array_chunk($array1, 30);
1
  • 2
    Loop through array2 and do an array_slice() from your array1 into a new array to get the necessary lengths Commented Apr 4, 2013 at 11:22

2 Answers 2

2

You should iterate over the array of chunk sizes and cut off an appropriate portion of your input array each time:

$input = range(0, 199);
$chunks = array(30, 40, 70, 30, 30);
$output = array();
$processed = 0;

while($chunks) {
    $processed += $size = array_shift($chunks);
    $output[] = array_slice($input, $processed, $size);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Hi Jon, Thanks for your help, in '$array1' i have randomly generated integers
Hi Jon, need to use $output[] = array_chunk($input, $processed, $size); Thanks!! :)
0

Why do not you try this

       $startingPoint = 0;
       foreach($array2 as $val)

       {
       for($i = $startingPoint ; $i < $startingPoint + $val ; $i++)
        { $array1[$i]  }
        $startingPoint += $val
       }

1 Comment

Hi Devesh, thanks!! But not getting required o/p

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.