简体   繁体   中英

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM