我有一个mysql查询,它会吐出以下数组:
Array
(
[0] => stdClass Object
(
[item1] => foo 0
[item2] => bar 0
[catid] => 3
)
[1] => stdClass Object
(
[item1] => foo 1
[item2] => bar 1
[catid] => 7
)
[2] => stdClass Object
(
[item1] => foo 2
[item2] => bar 2
[catid] => 10
)
[3] => stdClass Object
(
[item1] => foo 3
[item2] => bar 3
[catid] => 7
)
)
我想知道是否可以按“类别”对数组进行分组,所以不是重复的catids,每个对象里面都会有一个catid ..如果这有意义吗?所以说catid 7只会出现一次,其中有两个item1 / item2。
答案 0 :(得分:5)
这个怎么样?
foreach($results as $result) {
$by_category[$result->catid][] = $result;
}
print_r($by_category);
答案 1 :(得分:4)
您可以使用ouzo goodies:
执行此操作 $categories = Arrays::groupBy($results, Functions::extractField('catid'));
请参阅:http://ouzo.readthedocs.org/en/latest/utils/arrays.html#groupby
答案 2 :(得分:0)
$ret = array();
foreach ($array as $value) {
foreach ($value as $key => $item) {
if ($key == 'catid') continue;
$ret[$value['catid']][] = $item;
}
}