0

I need to write a PHP function to split an array into multiple arrays to accommodate it into a grid layout. In simplified terms, here's what I need to achieve:

Source data array:

$table = array(
'a','b','c','d',
'e','f','g','h',
'i','j','k','l',
'm','n','o','p',
'q','r','s','t',
'u','v','w','x',
'y','z');

I need to create a function, which takes this array an an input and also takes grid details as input (as mentioned below) and splits the array. For example:

grid_split($table, 1, 4); // 1st of 4 grid columns

Should return:

array('a','e','i','m','q','u','y');

and,

grid_split($table, 2, 4); // 2nd of 4 grid columns

Should return:

array('b','f','j','n','r','v','z');

similarly this,

grid_split($table, 1, 3); // 1st of 3 grid columns

Should return:

array('a','d','g','j','m','p','s','v','y');
4

2 回答 2

3

You could use array_slice function.

function grid_split($arr, $n, $grids) {
  $limit = count($arr) / $grids;
  return array_slice($arr, ($n - 1) * $limit, $limit);
}

Update: miss reading your question, the below is what you want.

function grid_split($arr, $n, $grids) {
  $ret = array();
  foreach ($arr as $key => $value) {
    if ($key % $grids === $n - 1) {
      $ret[] = $value;
    }
  }
  return $ret;
}
于 2012-08-10T06:44:32.330 回答
0

All you need is a run-of-the-mill for loop:

for($i = $n - 1, $count = count($arr); $i < $count; $i += $grids) {
    $ret[] = $arr[$i];
}
于 2012-08-10T07:10:38.547 回答