在PHP中使用嵌套查询生成JSON对象

时间:2014-08-09 18:16:27

标签: php mysql json join nested-loops

我试图从PHP传递JSON对象:

[{
    "id":"user1",
    "shops": [{
        "id":"shop1",
        "invoices": [{
            "id":"invoice1",
            "details": [{
                "id":"detailA"
            }, {
                "id":"detailB"
            }]
        }, {
        "id":"shop2",
        "invoices": [{
            "id":"invoice2",
            "details": [{
                "id":"detailC"
            }, {
                "id":"detailD"
            }]
        }]
    }]
}]

我有这个功能并且它正常工作,但是当数据库返回大量记录时,我的内存限制已经耗尽。我不想增加内存限制。什么是最佳做法?

function loadusers() {
    $return = array();

    $query = "SELECT u.id FROM users u";
    $users = mysql_query($query);

    while($user = mysql_fetch_assoc($users)) {
        $query = "SELECT s.id FROM shops s WHERE s.id_user = ".$user['id'];
        $shops = mysql_query($query);

        while($shop = mysql_fetch_assoc($shops)) {                
            $query = "SELECT i.id FROM invoices i WHERE i.id_shop = ".$shop['id'];
            $invoices = mysql_query($query);

            while($invoice = mysql_fetch_assoc($invoices)) {                
                $query = "SELECT d.id FROM invoice_details d WHERE d.id_inv = ".$invoice['id'];
                $details = mysql_query($query);

                while($detail = mysql_fetch_assoc($details)) {                
                    $invoices['details'][] = $detail;
                }

                $shop['invoices'][] = $invoice;
            }

            $user['shops'][] = $shop;
        }

        $return[] = $user;
    }

    return $return;
}

提前致谢。

跟着小说回答:

我创建了新查询:

SELECT
    u.id as id_user, 
    s.id as id_shop,
    i.id as id_invoice,
    d.id as id_detail
FROM 
    users u LEFT JOIN shops s ON s.id_user = u.id
    LEFT JOIN invoices i ON i.id_shop = s.id
    LEFT JOIN invoice_details d ON d.id_invoice = i.id

结果:

Query result

是否有语法糖将其转换为上述预期的JSON对象,还是我必须手动将结果解析为PHP数组然后执行json_encode

1 个答案:

答案 0 :(得分:2)

您可以使用 JOINS 进行一次查询,并且您不需要循环,查询您的情况:

SELECT 
    users.id as uid, 
    shops.id as sid,
    invoices.id as iid,
    invoice_details.id as did
FROM 
    users INNER JOIN shops ON shops.id_user = users.id,
    invoices INNER JOIN shops ON invoices.id_shop = shops.is,
    invoice_details INNER JOIN invoices ON invoice_details.id_inv = invoices.id;

根据你的需要,你可能会更好地使用另一个连接(不是内部),所以更多关于连接: http://blog.codinghorror.com/a-visual-explanation-of-sql-joins/