0

I have some code which is used to split 1 array in to multiple arrays based on key sequence. I want the 1 array to split in to multiple arrays just like the below code.

This is the array,

$weekday_array = array(
 1 => 'Monday',
 2 => 'Tuesday',
 3 => 'Wednesday',
 5 => 'Friday',
 6 => 'Saturday'
 );

I want output like this,

$arr1 = array(
 1 => 'Monday'
 2 => 'Tuesday'
 3 => 'Wednesday'
);
$arr2 = array(
 5 => 'Friday',
 6 => 'Saturday'
)
Pammm
  • 53
  • 6
  • 2
    And what is the rule which says where you want to make the split? – Jirka Hrazdil Nov 23 '16 at 11:24
  • Possible duplicate of [Split Array into Smaller Arrays Based on Value of Key?](http://stackoverflow.com/questions/6382362/split-array-into-smaller-arrays-based-on-value-of-key) – Veerendra Nov 23 '16 at 13:28

3 Answers3

1

use array_slice with 4th parameter true or array_chunk with 3rd parameter true, according to your requirements

<?php
$weekdays = [
 1 => 'Monday',
 2 => 'Tuesday',
 3 => 'Wednesday',
 5 => 'Friday',
 6 => 'Saturday'
];

$weekdays_groups = array_chunk($weekdays, 3, true);

var_dump($weekdays_groups[0], $weekdays_groups[1]);
1

What is the rule you need to make the split? The following code is working for just your example. You may have to change the code according to rule which you need.

<?php
$weekday_array = array(
 1 => 'Monday',
 2 => 'Tuesday',
 3 => 'Wednesday',
 5 => 'Friday',
 6 => 'Saturday'
 );

$new_array=array_chunk($weekday_array,3);

$arr1=$new_array[0];
$arr2=$new_array[1];
?>
Ranuka
  • 273
  • 3
  • 17
0
$result=array(array());
for ($weekdays as $w)
{
    if ($a=='Wednesday')
         $result[]=array();
    $result[count($result)-1][]=$a;
}

Where ($a=='Wednesday') should be replaced with your splitting criterion

Blair d
  • 78
  • 5