我遇到像这样的MySQL查询:
如何在PHP中按类别分组?
数据库方案:
MySQL查询:
$query = "SELECT cat.category_name, ch.channel_name
FROM `type_categ` tc , `categories` cat , `channels` ch
WHERE cat.category_id = tc.category_id AND ch.channel_id = tc.channel_id
ORDER BY cat.category_name ASC"
输出:
var_dump($category)
array(x) {
[0]=> array(2) {
["category_name"]=> string(8) "Category1"
["channel_name"]=> string(15) "Item1"
}
[1]=> array(2) {
["category_name"]=> string(8) "Category1"
["channel_name"]=> string(17) "Item2"
}
[2]=> array(2) {
["category_name"]=> string(8) "Category1"
["channel_name"]=> string(10) "Otem 5"
}
... ...
[x]=> array(2) {
["category_name"]=> string(8) "Category x"
["channel_name"]=> string(10) "Item x"
}
}
答案 0 :(得分:1)
您可以以您想要的格式迭代创建数组的数据。
这样的事可能是(working examle here);
<?php
$raw_data = array(
array('category_name' => 'Category1', 'channel_name' => 'Item 1'),
array('category_name' => 'Category3', 'channel_name' => 'Item 2'),
array('category_name' => 'Category1', 'channel_name' => 'Item 2'),
array('category_name' => 'Category3', 'channel_name' => 'Item 1'),
array('category_name' => 'Category2', 'channel_name' => 'Item 2'),
array('category_name' => 'Category2', 'channel_name' => 'Item 1')
);
$sorted = array();
foreach ($raw_data as $k => $v) {
if(!array_key_exists($v['category_name'], $sorted )) {
$sorted[$v['category_name']] = array();
}
$sorted[$v['category_name']][] = $v['channel_name'];
sort($sorted[$v['category_name']]);
}
ksort($sorted);
print_r($sorted);
?>
答案 1 :(得分:1)
使用foreach并将其分配给新阵列。
$newOptions = array();
$i=1;
foreach ($category as $option) {
$cname = $option['category_name'];
$itemname = $option['channel_name'];
$newOptions[$cname][$i] = $itemname;
$i++;
}