我已将$ data ['items']发送到我的视图,该视图创建了一个充满对象的数组,我可以用foreach循环回显。
foreach($items as $row)
{
echo $row->NAME . " - " . $row->COLOUR . "<br>";
}
我想要做的是将它们以颜色名称作为标题标记以组的形式回显给浏览器,然后启动该颜色的循环。我只是不确定要做什么类型的循环,或者我应该在循环中有循环?
BLUE
-item 1
-item 3
RED
-item 2
-item 4
-item 5
答案 0 :(得分:0)
你可能想要一个临时的二维数组:
$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 />";
}
答案 1 :(得分:0)
$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 />';
}