从查询中返回对象数组

时间:2016-03-03 11:51:31

标签: php

我目前有以下my_sql逻辑:

<input type="checkbox" name="items[]" value="coinpurse">coinpurse
<input type="checkbox" name="items[]" value="jacket">jacket
<input type="checkbox" name="items[]" value="tumbler">tumbler
<button type ="submit" name="submit" value="send to database"> SEND TO DATABASE </button>

这会返回一个如下数组:

$results = $wpdb->get_results('
                        SELECT
                            catname as subcatname,categoryid, 
                            (SELECT 
                                catname 
                            FROM 
                                isc_categories 
                            WHERE 
                                categoryid= '.(int)$id.') as catname
                        FROM
                            isc_categories
                        WHERE
                            catparentid = '.(int)$id.'
                        AND  
                            catvisible=1
                        ORDER BY
                            subcatname' );

$rs = mysql_query($query);

while ($row = mysql_fetch_object($rs)) {

var_dump($row);

}

}

但是,我想以这种格式返回我的结果:

array(1) {
  [0]=>
  object(stdClass)#16 (3) {
    ["subcatname"]=>
    string(29) "Category Name: D.C Ice Makers"
    ["categoryid"]=>
    string(4) "1113"
    ["catname"]=>
    NULL
  }
}
array(1) {
  [0]=>
  object(stdClass)#17 (3) {
    ["subcatname"]=>
    string(33) "Category Name: Parry Boiling Tops"
    ["categoryid"]=>
    string(4) "1114"
    ["catname"]=>
    NULL
  }

我尝试过使用“mysql_fetch_object”,但我很难以我需要的格式返回结果。感谢

1 个答案:

答案 0 :(得分:0)

查询错误。试试这样:

SELECT c.catname as subcatname,
       c.categoryid,
       cc.catname
FROM isc_categories c
JOIN isc_categories cc
  ON cc.categoryid = c.catparentid
WHERE c.catparentid = ' . $id . '
  AND c.catvisible = 1
ORDER BY c.catname

如果您使用相同的查询仅获取顶级父类别(LEFT JOIN为0时),请使用$id