How to create an multidimensional array in VB.NET or PHP
I have a data set that is setup for comments. I have levels and a sort column but now I would like to either get this in an array or display it somehow in a meaningful way:
id comment Parentid Level sortcol
2 Test NULL 0 0x00000002
4 This is the Second NULL 0 0x00000004
5 First Reply 4 1 0x000000040005
7 Reply to first reply 5 2 0x0000000400050007
6 Second Reply 4 1 0x000000040006
8 Reply to second comment 4 1 0x000000040008
How do I get this into an array in PHP or VB.net (I don't have a preference and use both regularly).
I want an array that looks like this (I am just specifying the ids:
array([0]
[id]=>2
[1]
[id]=>4
array([0]
[id]=>5
array([0]
[id]=>7
)
开发者_JAVA技巧 [1]
[id]=>6
[2]
[id]=>8
)
)
The data is a SQL result.
Note: I'm assuming, despite its being unspecified, that you need a 'children' key in addition to 'id', to contain the subarrays.
// Skip list, to hold data as well as reference to nested list later
$flat = array ();
while ($row = mysql_fetch_assoc($result))
$flat[$row['id']] = $row;
$root = array ();
foreach ($flat as $id => $row)
{
// Get reference to parent, or root if none set
if (!$row['Parentid'])
$parent =& $root;
else
$parent =& $flat[$row['Parentid']]['ref'];
if (!$parent['children'])
$parent['children'] = array ();
// Append new child
$parent['children'][] = array ('id' => $id);
// Add newly appended child to skip list
$flat[$id]['ref'] =& end ($parent['children']);
}
// Final nested list
$nested = $root['children'];
For this to work, all parents must appear before their children in the flat list
You should use a Typed DataSet in VB .Net.
Typed DataSets will allow you to do it with almost no code, and are much easier to use than a 2-dimensional array.
To get started, create a new VB.Net project, add a Typed DataSet, and follow the instructions.
精彩评论