2011-05-18 59 views
2

我不知道如何做一个父母,孩子(通过一个ID)被放入一个新的数组从数组(由数据库加载)。制作一个数组产生父母和孩子的记录

我需要它是这样的:

+- Parent - ID: 4 
| 
+---- Child record 
+---- Child record <-- these children have a parent_id of 4 
+---- Child record 
| 
+- Parent - ID: 5 
| 
+---- Child record 
+---- Child record 
+---- Child record 
+---- Child record <-- these children have a parent_id of 5 
+---- Child record 
| 
+- Parent - ID: 7 
| 
+---- Child record 
+---- Child record <-- these children have a parent_id of 7 
+---- Child record 

等等,从数据库加载的记录是这样的:

Array 
(
    [0] => Array 
     (
      [id] => 1 
      [info] => this is a child, since sub is 1 and parent_id contains a number 
      [sub] => 1 
      [parent_id] => 4 
     ) 

    [1] => Array 
     (
      [id] => 2 
      [info] => this is a parent, since sub is 0 and parent_id does not contain a number 
      [sub] => 0 
      [parent_id] => 
     ) 

    [2] => Array 
     (
      [id] => 1 
      [info] => this is a child, since sub is 1 and parent_id contains a number 
      [sub] => 1 
      [parent_id] => 4 
     ) 

.... more records 

的SQL以升序方式由行排序id,这个新数组包含记录父母和孩子的基本内容。

+0

很抱歉,如果我没有意义的关键,我累了如果您需要任何澄清,请添加更多。 – MacMac 2011-05-18 15:18:52

+0

对不起,这没有意义。你正试图从数据库查询中创建数组?或者你有另一种你想在PHP中转换的数据结构? – Cfreak 2011-05-18 15:22:52

+0

其实,当我更全面地看待你的问题时,我注意到了一个信息是父母的奇怪实例,你想如何接近你想要的信息与孩子关联? – 2011-05-18 15:28:58

回答

2
foreach($dbArray as $row) 
{ 
    if($row['parent_id'] != "") 
    { 
     $parentArray[$row['parent_id']][]['child'] = $row['info']; 

    } 
    else 
    { 
     $parentArray[$row['id']]['parent'] = $row['info']; 
    } 

} 

这是在父ID是儿童信息 的阵列产生的阵列会是这个样子

Array(
/*parent id*/ 
    [0]=>Array(
     [parent] => //whatever info 
     [0] => Array(
       [child]=> //whatever child info 
        ) 

      ) 
    )  
+0

对不起,您能解释一下,请提供更多代码。 – MacMac 2011-05-18 15:26:33

+0

看起来不错,但我相信OP需要整个儿童记录,而不仅仅是info属性。 – 2011-05-18 15:26:46

+0

你想要数组中的所有父级信息和所有子级信息吗? – 2011-05-18 15:31:07