5

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!

2 Answers 2

7

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;
3
  • +1, Touche. I forgot about that function. I actually like that, if it's arbitrary grouping. Commented Jun 23, 2011 at 15:56
  • +1 array_chunk (very useful function while playing with arrays :)) Commented Jun 23, 2011 at 16:11
  • Cool stuff. Works perfectly and would be the complete solution except for the fact that it creates numerically indexed array keys. I can probably iterate over the array after the fact and prepend "Group" to each key name. Commented Jun 23, 2011 at 16:35
1
$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.

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.