开发者

Looping through array objects to output

I have sent $data['items'] to my view which has created an array full of objects which I can echo with a foreach loop.

foreach($items as $row)
  {
    echo $row->NAME . " - " . $row->COLOUR . "<br>";
  }

what I want to do is echo them to the brows开发者_如何学Goer in groups with the name of the colour as a header tag then start the loop for that colour. I'm just not sure what type of loop to do or should I have a loop within a loop?

BLUE

-item 1

-item 3

RED

-item 2

-item 4

-item 5


$list = array();
foreach($items as $row)
{
  $list[$row->COLOUR][] = $row->NAME;
}

$header = null;
foreach($list as $item)
{
  if($header != $item->COLOUR)
  {
    echo '<h3>' . $item->COLOUR . '</h3>';
    $header = $item->COLOUR;
  }
  echo '- ' . $item->NAME . '<br />';
}


You probably want an interim two-dimensional array:

$tmp = array();
foreach($items as $row)
{
    // this code groups all items by color
    $name = $row->NAME;
    if( !isset ($tmp[ $name ] ) ) $tmp[ $name ] = array();
    $tmp[ $name ][] = $row->COLOUR;
}

foreach( $tmp as $color => $items )
{
   // colors are now keys to the temp array
   echo $color;
   // these are all of the items grouped under the current color
   foreach( $items as $item )
   {
       // output the item.
       echo "<br /> - $item";
   }
   echo "<br />";
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜