我在论坛上进行了一些搜索,但我的问题没有任何好的答案。如果我错过了什么,请随时将我链接到问题!
我需要做的很简单:一个函数,它返回一个包含我的类别和项目的完整树的数组。我只有 1 个深度(项目和 cat_id),所以不涉及递归(尽管如果你有递归解决方案,我很乐意接受)。
现在,我已经这样做了,但这很糟糕,因为我做了多个查询......
function build_tree()
{
global $wpdb;
$cats = $wpdb->get_results("SELECT * FROM wp_catering_cats");
foreach($cats as &$cat)
{
$id = $cat->id;
$cat->items = $wpdb->get_results("SELECT * FROM wp_catering_items WHERE cat_id = $id");
}
return $cats;
}
我的表格非常简单:
wp_餐饮项目
id, cat_id, name, price
wp_餐饮猫
id, name
这是我想要的结果数组的一个例子:
Array
(
[0] => array
(
[id] => 1
[name] => Cat #1
[items] => Array
(
[0] => array
(
[id] => 1
[cat_id] => 1
[name] => Item #1
[price] => 5
),
...
)
),
...
);
如果有不清楚的地方,请随时发表评论!
谢谢!
编辑
我已经使用下面的代码进行了一些修改,但我很确定有一种更简洁的方法可以做到这一点。必须订购一个 DESC 和一个 ASC 听起来不太对。
function build_tree()
{
global $wpdb;
$cats = $wpdb->get_results("SELECT * FROM wp_catering_cats ORDER BY id DESC");
$items = $wpdb->get_results("SELECT * FROM wp_catering_items ORDER BY cat_id ASC");
$item = array_pop($items);
foreach($cats as &$cat)
{
while($item->cat_id == $cat->id)
{
$cat->items[] = $item;
$item = array_pop($items);
}
}
print_r($cats);
}