I have an array that need to be sliced in the below formate.
$arr =[val1,val2,val3,val4,..........];
$result = [
[ val1, val2, val3 ], /* First 3 elements */
[ val4, val5, val6 ], /* next 3 elements */
[ val7 ], /* next 1 element */
[ val8 ], /* next 1 element */
[ val9, val10], /* next 2 elements */
[ val11, val12 ], /* next 2 elements */
[ val13, val14, val15 ], /* next 3 elements */
[ val16, val17, val18 ], /* next 3 elements */
[ val19 ], /* next 1 element */
[ val20 ], /* next 1 element */
[ val21, val22], /* next 2 elements */
[ val23, val24 ], /* next 2 elements */ and so on...
/*repeat same with next 3,3,1,1,2,2 elements */
]
so I need to convert array in above formate because of my html element showing data in 3,3,1,1,2,2 formate.
Thanks
2
Answers
Just use while loop and iterate over the data. You can use the pattern as a repeatable counter.
Demo: https://3v4l.org/mnfhP
[[1,2,3],[4,5,6],[7],[8],[9,10],[11,12],[13,14,15],[16,17,18],[19],[20],[21,22],[23,24],[25,26,27],[28,29,30],[31],[32],[33,34],[35,36],[37,38,39]]
This solution breaks the original data into chunks according to the sum of all of the individual bits. Then for each chunk – it again splits it down.
Although there are nested loops, it’s operating on chunks of data and not individual elements.
gives…
[[1,2,3],[4,5,6],[7],[8],[9,10],[11,12],[13,14,15],[16,17,18],[19],[20],[21,22],[23,24],[25,26,27],[28,29,30],[31],[32],[33,34],[35,36],[37,38,39],[40]]