1

我在论坛上进行了一些搜索,但我的问题没有任何好的答案。如果我错过了什么,请随时将我链接到问题!

我需要做的很简单:一个函数,它返回一个包含我的类别和项目的完整树的数组。我只有 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);
}
4

1 回答 1

2

如果你只是想优化,那就做简单的事情,而不是只抓取你所在的特定猫的物品,一次抓取所有物品,并按 catID 排序。然后遍历你的猫,并从你的项目结果中弹出项目,直到你击中下一只猫。

function build_tree()
{
    global $wpdb;

    $cats = $wpdb->get_results("SELECT * FROM wp_catering_cats order by cat_id asc");
    $items = $wpdb->get_results("SELECT * FROM wp_catering_items ORDER BY cat_id asc");

    foreach($cats as &$cat)
    {
      $id = $cat->id;
      $item = array_pop($items)
      while($item['cat_id'] == $id)
      {
        $cats->item[] = $item;
        $item = array_pop($items)
      }
      #do a little bookkeeping so you next cat gets its first item, and zero item cats get skipped.

    }
}

更新:感谢您的评论.. 忘记在 while 循环中添加弹出!

第二次更新:如果您不希望反向排序成为问题,请使用 array_shift 而不是 array_pop...

于 2010-07-06T19:51:35.863 回答