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');

2 Answers 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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

grid_split($table, 1, 4) returns Array ( [0] => a [1] => b [2] => c [3] => d [4] => e [5] => f ) expected is Array ( [0] => a [1] => e [2] => i [3] => m [4] => q [5] => u [6] => y )
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];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.