How to get an hierarchical php structure from a db table, in php array, or JSON [duplicate]

人走茶凉 提交于 2019-12-04 18:38:52

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;    
    }
}

The method you're using in storing your data is called Adjacency List model. To be able to achieve what you require. Follow these steps.

1) Retrieve the parent elements and save them to an array / hash.

2) Iterate through the parent array and retrieve child elements using the id of the parent. Save the result to an array and append as element of the current parent array using "children" as key.

3) JSON encode the resulting array.

<?php
    $sql    = "SELECT * FROM yourtable WHERE PARENT is NULL or PARENT = 0";
    $result = $db->query($sql);  //a valid MySQL database adapter with a 
                                 //"query" method which returns the full result set.
    $arr = array();
    foreach($result as $row) {
       $sql = "SELECT * FROM yourtable WHERE PARENT = {$row['id']}";
       $result2 = $db->query($sql);
       $row["children"] = $result2;
       $arr[] = $row;
    }
    echo json_encode($arr);
?>

For more info about retrieving data hierarchy on these type of table, read Rum's post on Retrieving Data Hierarchies on a SQL Table.

Also, take precaution in this implementation. Although it looks easy to implement, watch out for the number of iterations involving external resource calls, in this case your database server. Iteratively calling queries beats the crap out of it causing performance problems in the future. If that is the case, you can apply a technique similar to Kendall Hopkins (though I'm not sure why he used by-ref call on $row). More info about iterative external resource calls here.

<?php
$sql = "SELECT * FROM yourtable";
$result = $db->query($sql);
$arr = array();
//re-index the result array based on their actual IDs
foreach ($result as $row) {
    $arr[$row['ID']] = $row;
}
foreach ($arr as $item) {
    if (!empty($item["PARENT"]) && $item["PARENT"] != 0) {
       $arr[$item["PARENT"]]["children"][] = $item;
       //unset the discovered child item to clean-up array and release memory allocation 
       unset($arr[$item["ID"]]);
    }
}
echo json_encode($arr);
?> 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!