1

可能重复:
将数据库结果转换为数组

嗨,伙计们,你能帮帮我吗?如何从 db 表、php 数组或 JSON 中获取分层 php 结构,但格式如下:

[
  {
     "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、PARENT、ORDER、TITLE

你能帮我解决这个问题吗?我要疯了才能得到这个。

提前谢谢了。丹尼尔

4

2 回答 2

2

两遍 foreach 可以解决问题。这将递归地将所有孩子链接到他们的父母。

$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;    
    }
}
于 2010-05-10T03:12:17.160 回答
0

您用于存储数据的方法称为邻接列表模型。为了能够达到你所要求的。按着这些次序。

1)检索父元素并将它们保存到数组/哈希中。

2) 遍历父数组并使用父元素的 id 检索子元素。将结果保存到一个数组中,并使用“children”作为键附加为当前父数组的元素。

3) JSON 编码结果数组。

<?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);
?>

有关在这些类型的表上检索数据层次结构的更多信息,请阅读 Rum关于在 SQL 表上检索数据层次结构的帖子。

此外,在此实施中采取预防措施。尽管它看起来很容易实现,但请注意涉及外部资源调用的迭代次数,在本例中是您的数据库服务器。迭代调用查询可以避免在未来导致性能问题。如果是这种情况,您可以应用类似于 Kendall Hopkins 的技术(尽管我不确定他为什么对 $row 使用 by-ref 调用)。有关迭代外部资源调用的更多信息在这里。

<?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);
?> 
于 2010-05-10T03:22:28.407 回答