本文介绍了如何从一个数据库表中的层次结构的PHP,在PHP数组,或JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  

大家好,你能不能帮我。如何从一个数据库表中的层次结构的PHP,在PHP数组,或JSON,但具有以下格式:

Hi guys, can you please help me. How to get an hierarchical php structure from a db table, in php array, or JSON, but with the following format:

[{属性:{ID:111},数据:有些结题,孩子:[{属性:{ID:555},数据:这里的一个子节点标题}],状态:打开},{属性:{ID:222},数据:其他主节点,孩子 :[{属性:{ID:666},数据:另一个子节点}],国家:开放}]

[{ "attributes" : {"id" : "111"}, "data" : "Some node title", "children" : [ { "attributes" : { "id" : "555"}, "data" : "A sub node title here" } ], "state" : "open" }, { "attributes" : {"id" : "222"}, "data" : "Other main node", "children" : [ { "attributes" : { "id" : "666"}, "data" : "Another sub node" } ], "state" : "open" }]

我的SQL表包含的字段:ID,父,秩序,标题

My SQL table contains the fields: ID, PARENT, ORDER, TITLE

能否请您帮助我?我要疯了试图让这个。

Can you please help me with this? I'm going crazy trying to get this.

提前非常感谢。
丹尼尔

Many thanks in advance. Daniel

推荐答案

二阶段的foreach的伎俩。这将递归所有子链接到他们的父母。

Two pass foreach does the trick. This will link all child to their parents recursively.

$structure = array();
foreach( $array as $row ) { //add rows to array by id
    $structure[ $row["id"] ] = $row + array( "children" => array() );
}
foreach( $structure as &$row ) { //link children to parents
    if( ! is_null( $row["parent"] ) ) {
        $structure[ $row["parent"] ]["children"][] =& $row;    
    }
}

这篇关于如何从一个数据库表中的层次结构的PHP,在PHP数组,或JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 11:39