我有 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
)
)