簡體   English   中英

如何在VB.NET或PHP中創建多維數組

[英]How to create an multidimensional array in VB.NET or PHP

我有一個用於評論的數據集。 我有一個級別和一個排序列,但現在我想將其放入數組中或以某種有意義的方式顯示它:

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

如何將其放入PHP或VB.net的數組中(我沒有偏好,並且經常使用兩者)。

我想要一個看起來像這樣的數組(我只是在指定id:

array([0]
         [id]=>2
      [1]
         [id]=>4
             array([0]
                      [id]=>5
                       array([0]
                                [id]=>7
                            )
                   [1]
                      [id]=>6
                   [2]
                      [id]=>8
                   )
       )

數據是SQL結果。

您應該在VB .Net中使用類型化數據集

類型化數據集將讓你幾乎沒有任何代碼做,更容易比2維數組使用。

首先,創建一個新的VB.Net項目,添加一個Typed DataSet,然后按照說明進行操作。

注意:我假設,盡管未指定,但除了'id'外,還需要'children'鍵來包含子數組。

// 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'];

為此,所有父母必須在平面列表中出現在其子女之前

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM