2010-07-06 96 views
1

我在论坛上做了一些搜索,没有为我的问题找到任何好的答案。如果我错过了一些东西,请随时将我与这个问题联系起来!类别和项目1大阵列

我需要做的是简单:一个函数,返回我的类别和项目的完整树的数组。我只有1个深度(item和一个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_catering_items

id, cat_id, name, price 

wp_catering_cats

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); 
} 

回答

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_pop array_shift如果你不想反向排序是一个问题......

+0

它应该是更快的无秩序运行查询BY和创建数组$ catsById [$ CATID = $猫;以便通过id访问类别。 – Naktibalda 2010-07-06 19:56:50

+0

您只在每次迭代中弹出一次该项目?因为它看起来像会造成无限循环。 – allaire 2010-07-06 20:17:03

+0

看看我的帖子中的编辑,你必须首先在foreach外弹出,否则你会弹出新猫的第一项(在while循环中打破的)。另外,由于foreach从头开始,因此您需要对DESC类别进行排序......必须有一个更好的方法来执行此操作:o但是肯定的是,此解决方案仍比我的第一个方案更好... – allaire 2010-07-06 20:39:53