Making an array producing parents and children of records
I cannot figure out how to make a parent, child (by an id) that be put into an new array from an array (loaded by a database).
I need it to be like this:
+- 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 <--开发者_如何学C these children have a parent_id of 7
+---- Child record
And so on, the record loaded from the database looks like this:
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
The SQL is ordered in ascending mode by the row id
, the new array containing parents and child of records what it's basically for.
foreach($dbArray as $row)
{
if($row['parent_id'] != "")
{
$parentArray[$row['parent_id']][]['child'] = $row['info'];
}
else
{
$parentArray[$row['id']]['parent'] = $row['info'];
}
}
this is where the parent id is the key for the array of child info The resulting array would look something like this
Array(
/*parent id*/
[0]=>Array(
[parent] => //whatever info
[0] => Array(
[child]=> //whatever child info
)
)
)
精彩评论