【问题标题】:Looping through array objects to output循环遍历数组对象以输出
【发布时间】:2011-07-19 21:34:41
【问题描述】:

我已将 $data['items'] 发送到我的视图,该视图创建了一个充满对象的数组,我可以使用 foreach 循环来回显这些对象。

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

我想要做的是将它们以颜色名称作为标题标签分组回显到浏览器,然后启动该颜色的循环。我只是不确定要执行哪种类型的循环,或者我应该在循环中添加一个循环?

蓝色

-项目 1

-项目 3

红色

-项目 2

-项目 4

-项目 5

【问题讨论】:

  • 你能用数组的 print_r 更新问题吗?

标签: php codeigniter


【解决方案1】:
$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 />';
}

【讨论】:

    【解决方案2】:

    你可能想要一个临时的二维数组:

    $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 />";
    }
    

    【讨论】:

      猜你喜欢
      • 2016-09-07
      • 1970-01-01
      • 1970-01-01
      • 2020-07-19
      • 2016-07-28
      • 2017-01-29
      • 2015-10-15
      相关资源
      最近更新 更多