Reputation: 892
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');
Upvotes: 0
Views: 781
Reputation: 7626
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];
}
Upvotes: 0
Reputation: 160893
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;
}
Upvotes: 3