Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Having some trouble coming up with the right combination of count and foreach for a multidimensional array.

I'm currently doing the following to create an associative array from my db's returned result:

$sql = "SELECT g.id, g.shortname FROM games g ORDER BY g.id ASC";
        $query = $this->db->query($sql);

        if($query->num_rows() > 0):
            foreach($query->result() as $row):
                $data[$row->id] = $row->shortname;
            endforeach;
        return $data;
        else:
            return false;
        endif;

This of course produces the following array (which works fine; semi-faux code):

array ( [1] => CoolGame, [2] => AnotherGame, [3] => BetterGame, [4] => UglyGame)

....and so on

But what I want to do is automatically break up results (based on a count var/limiter) into groups via a multidimensional array like so:

array (Group 1 => 
         array([1] => CoolGame [2] => AnotherGame),
       Group 2 =>  
         array([3] => BetterGame [4] => UglyGame)
)

So in that example, my $depth_count = 2;

In case anyone is interested, I'm doing this to work with auto-generated <optgroup> tags for a multi select via CI's form helper's form_multiselect() function. Need some help with tweaking my PHP to allow for this. Thanks!

like image 535
k00k Avatar asked Jun 23 '11 15:06

k00k


2 Answers

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;
like image 54
Ozair Kafray Avatar answered Oct 27 '22 00:10

Ozair Kafray


$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.

like image 42
Brad Christie Avatar answered Oct 26 '22 22:10

Brad Christie