我有4个设置为具有分层数据的表。我试图通过联接取回数据,并找到一种可重用的方法,以从结果中获取多维数组,将来可以在其他表布局中使用该多维数组。最终,我想将其作为json吐出。有什么好方法吗?

这是我的mySQL代码的示例:

SELECT

    table1.name as level1_name,
    table1.id as level1_id,
    table2.name as level2_name,
    table2.id as level2_id,
    table3.name as level3_name,
    table3.id as level3_id,
    table4.name as level4_name,
    table4.id as level4_id

FROM
    table1

LEFT JOIN table2    on table2.parentid      = table1.id
LEFT JOIN table3    on table3.parentid      = table2.id
LEFT JOIN table4    on table4.parentid      = table3.id

WHERE
    table1.id = 5


我希望看到这样的结果:

Table1_name
{
    Table2_name {
        Table3_name {
            Table4_name,
            Table4_othername
        }
    }
    Table2_othername {
        Table3_othername {
            Table4_othername,
            Table4_otherothername
        }
    }
}


但是我得到的是:

Array
(
    [0] => stdClass Object
        (
            [level1_name] => Lorem
            [level1_id] => x
            [level2_name] => Ipsum
            [level2_id] => x
            [level3_name] => Dolor
            [level3_id] => x
            [level4_name] => Eimet
            [level4_id] => x
        )

    [1] => stdClass Object
        (
            [level1_name] => Lorem
            [level1_id] => x
            [level2_name] => Ipsum
            [level2_id] => x
            [level3_name] => Dolor
            [level3_id] => x
            [level4_name] => Eimet
            [level4_id] => x
        )

    [2] => stdClass Object
        (
            [level1_name] => Lorem
            [level1_id] => x
            [level2_name] => Ipsum
            [level2_id] => x
            [level3_name] => Dolor
            [level3_id] => x
            [level4_name] => Eimet
            [level4_id] => x
        )
)

最佳答案

可以单独查询。或使用字段名称的前缀将其添加到不同的对象中
将level1_id重命名为level_1_id,这样更容易使用爆炸和for循环解析数字

关于php - 如何从包含多个联接的mysql查询中获取php中的多维数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19011414/

10-11 07:02