douwen7516 2013-01-19 19:35
浏览 16
已采纳

如何在类别标题中显示类别项目

I have an array like below

Array
(
    [0] => stdClass Object
        (
            [id] => 1
            [cat_id] => 1
            [item_name]=>test1
            [cat_name] => Normal
        )

    [1] => stdClass Object
        (
            [id] => 2
            [cat_id] => 2
            [item_name]=>test2
            [cat_name] => Featured
        )

    [2] => stdClass Object
        (
            [id] => 3
            [cat_id] => 2
            [item_name]=>test3
            [cat_name] => Featured
        )  
)  

And I want the result to look like this

Normal

test1

Featured

test2  |  test3

I have try this so far:

<?php
foreach($rows as $row){
    echo '<h2>'.$row->cat_name.'</h2>';
    echo '<p>'.$row->item_name.'</p>';
}
?>

But it shows the heading with each of the item.Can someone help me to sort this out.

Thanks

  • 写回答

1条回答 默认 最新

  • duandong1869 2013-01-19 19:46
    关注

    So you want to group them? Here's a function for that:

    function groupBy($arr, $func) {
        $groups = [];
    
        foreach($arr as $item) {
            $group = $func($item);
    
            if(array_key_exists($group, $groups))
                $groups[$group][] = $item;
            else
                $groups[$group] = [$item];
        }
    
        return $groups;
    }
    

    Use it like so:

    $groups = groupBy($rows, function($row) { return $row->cat_name; });
    
    foreach($groups as $name => $items) {
        echo "<h2>$name</h2>";
    
        foreach($items as $item)
            echo "<p>{$item->item_name}</p>";
    }
    

    And here's a demo. If you don't have the luxury of PHP 5.3, then you can make it more specialized:

    function groupBy($arr, $prop) {
        $groups = array();
    
        foreach($arr as $item) {
            $group = $item->$prop;
    
            if(array_key_exists($group, $groups))
                $groups[$group][] = $item;
            else
                $groups[$group] = array($item);
        }
    
        return $groups;
    }
    ...
    $groups = groupBy($rows, 'cat_name');
    
    foreach($groups as $name => $items) {
        echo "<h2>$name</h2>";
    
        foreach($items as $item)
            echo "<p>{$item->item_name}</p>";
    }
    

    Demo on PHP 5.2.17

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊