Reputation: 4711
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
Upvotes: 0
Views: 69
Reputation: 225291
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>";
}
Upvotes: 2