PHP - Create multidimensional array via a loop based on a count PHP - Create multidimensional array via a loop based on a count codeigniter codeigniter

PHP - Create multidimensional array via a loop based on a count


You can use php's array_chunk method. Notice its use in modified code below:

if($query->num_rows() > 0):    foreach($query->result() as $row):        $data[$row->id] = $row->shortname;    endforeach;    $data = array_chunk($data, 2);return $data;


$nGroup = 1; $curGroup = '';$nRow = 0;foreach ($query->result() as $row){  if ($nRow++ % 2 == 0){ // change 2 to your limiter    $curGroup = 'Group ' . $nGroup++;    $data[$curGroup] = array();  }  $data[$curGroup][$row->id] = $row->shortname;}

Something like that? Keep track of the row you're on, the current group your adding to, and the group name. Then, every 2nd (or Nth) set, switch groups.