我已经看到了其他关于此的问题,但与我的情况不太一样。我在 MySQL 中有下表:
term_id name slug taxonomy parent
1 Entry Form entry-form format 0
2 Page page format 3
3 Facebook facebook format 0
4 Entry Form facebook-entry-form format 3
5 Twitter twitter format 0
6 Single single format 2
我有以下 OBJECT 查询:
$formats = $wpdb->get_results($wpdb->prepare("
SELECT * FROM table t
WHERE t.taxonomy = 'format'
"));
我结束了以下数组:
Array ( [0] => stdClass Object ( [term_id] => 1 [name] => Entry Form [slug] => entry-form [taxonomy] => format [parent] => 0 ) [2] => stdClass Object ( [term_id] => 2 [name] => Page [slug] => page [taxonomy] => format [parent] => 3 ) [3] => stdClass Object ( [term_id] => 3 [name] => Facebook [slug] => facebook [taxonomy] => format [parent] => 0 ) [4] => stdClass Object ( [term_id] => 4 [name] => Entry Form [slug] => entry-form-facebook [taxonomy] => format [parent] => 3 ) [5] => stdClass Object ( [term_id] => 5 [name] => Twitter [slug] => twitter [taxonomy] => format [parent] => 0 ) [6] => stdClass Object ( [term_id] => 6 [name] => Single [slug] => single [taxonomy] => format [parent] => 2 ) ) 1
以上所有内容都需要转换为输出的分层列表,如下所示:
Entry Form
Twitter
Facebook
- Entry Form
- Page
-- Single
因此,我需要将数组 $formats 转换为基于父字段的分层数组。0 的父项表示它是顶级项目。因此,由于 Single 的父节点为 2,因此它是 Page 的子节点,而 Page 的父节点又是 3,并且是 Facebook 的子节点。
谁能帮我把我的数组变成一个分层数组,然后告诉我如何循环输出它?