将数组转换为二维数组并删除前11个条目
问题描述:
I have been trying to figure this out until my brain imploded. Im trying to sort an array.
The first 11 entries has to be removed, then the next 7 entries has to be placed in an new array and then the next 7 entries and so on. Until there is no more entries.
Short example:
Turn this:
Array (
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => 4
[5] => 5
[6] => 6
[7] => 7
[8] => 8
[9] => 9
[10] => 10
[11] => 11
[12] => 12
[13] => 13
[14] => 14
[15] => 15
[16] => 16
[17] => 17
[18] => 18
)
Into this:
Array (
[0] => Array (
[0] => 11
[1] => 12
[2] => 13
[3] => 14
[4] => 15
[5] => 16
[6] => 17
)
)
答
Something like this should do the trick:
$orig = array(...);
$i = 11; // start at offset 11
$remove = 7; // take off 7 at a time
$new = array();
while($i <= count($orig)) {
$new[] = array_slice($orig, $i, $remove);
$i += $remove;
}
$new will have your new multi-dimensionalized array
答
Why do a while
when you can do a for
$a = array(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20); // your array
$ret = array(); // new array
for($i=11; $i < sizeof($a); $i+=7)
$ret[] = array_slice($a, $i, 7);
答
You can use array_slice
to get a part and array_chunk
to chunk the leftover:
// take out the first 11 elements
$array = array_slice($array, 11);
// create chunks with 7 entries each
$array = array_chunk($array, 7);