2010-05-09 53 views
1

可能重复:
Turn database result into array如何获得从数据库表的分层结构的PHP,在PHP数组,或JSON

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

[ 
    { 
    "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,父,秩序,TITLE

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

非常感谢提前。 丹尼尔

+2

可能重复[打开数据库导致进入阵列(http://stackoverflow.com/questions/2794638/turn-database-result-into-array) – 2010-05-09 23:29:41

回答

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

有关在这些类型的表中检索数据的层次结构的详细信息,请阅读Retrieving Data Hierarchies on a SQL Table朗姆酒的帖子。

另外,在这个实现中要小心。虽然看起来很容易实现,但要注意涉及外部资源调用的迭代次数,在这种情况下是数据库服务器。迭代地调用查询会使其不堪重负,导致将来性能问题。如果是这样的话,你可以应用一种类似于肯德尔霍普金斯的技术(尽管我不确定他为什么使用by-ref调用$行)。有关更多信息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); 
?> 
+0

谢谢两位的帮助,但我测试本页面提供的所有3种解决方案都适用于只有2级深度的层次结构。但是我有一个树状结构,层次多层次,这里的解决方案在这种情况下不起作用。我认为它需要一个经常性的功能,但是不能正确地做。 :( – daniel 2010-05-10 20:49:52

+0

我设法找到一个非常好的解决方案,在这里使用类:http://stackoverflow.com/questions/2794638/turn-database-result-into-array/2795069#2795069 – daniel 2010-05-11 17:49:17

+0

是的,为了突破如果深度过深并导致性能问题,那么您可能需要重新考虑数据存储和表示,只要看看我引用的博客文章,就可以得到所有的你需要的信息,祝你好运! – walkthroughthecloud 2010-05-13 16:58:58