我有一个如下所示的数组
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
)
)
我希望结果看起来像这样
正常
test1
主要
test2 | test3
到目前为止我试过这个:
<?php
foreach($rows as $row){
echo '<h2>'.$row->cat_name.'</h2>';
echo '<p>'.$row->item_name.'</p>';
}
?>
但它显示了每个项目的标题。有人可以帮我解决这个问题。
由于
答案 0 :(得分:2)
所以你想把它们分组?这是一个功能:
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;
}
像这样使用它:
$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.如果你没有PHP 5.3的奢侈品,那么你可以使它更专业化:
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>";
}