制作一个阵列,产生父母和记录的孩子

时间:2011-05-18 15:18:28

标签: php arrays multidimensional-array

我无法弄清楚如何将一个父,子(通过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以升序模式排序,新数组包含父记录和子记录的基本内容。

1 个答案:

答案 0 :(得分: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
                   )

           )
      )