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 browser 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 />';
}

您可能需要一个临时二维数组:

$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 />";
}
链接地址: http://www.djcxy.com/p/47802.html

上一篇: 将mysql查询与子查询结果合并为一个PHP数组

下一篇: 通过数组对象循环输出