通过父ID从平面数组创建嵌套数组

时间:2014-01-09 13:39:46

标签: php arrays

我想将我的平面数组制作成嵌套数组,但我似乎无法做到这一点; /

我尝试将其嵌套的代码:

<?php
$link = mysqli_connect("localhost", "db_phpnav", "jeXS9ftZhmJdzRWd", "db_phpNav");
$sql = "SELECT ID, PID, Naam  FROM tb_nav";
$result = mysqli_query($link, $sql);

function convertToTree(array $flat, $idField = 'ID',
                        $parentIdField = 'PID',
                        $childNodesField = 'childNodes') {
    $indexed = array();

    foreach ($flat as $row) {
        $indexed[$row[$idField]] = $row;
        $indexed[$row[$idField]][$childNodesField] = array();
    }


    $root = null;
    foreach ($indexed as $id => $row) {
        $indexed[$row[$parentIdField]][$childNodesField][$id] =& $indexed[$id];
        if (!$row[$parentIdField]) {
            $root = $id;
        }
    }

    return array($root => $indexed[$root]);
}

$rows = array();

while($row = mysqli_fetch_assoc($result)) {
    $rows[] = $row;
}

convertToTree($rows);

?>

它给出的数组。它显然不符合我的意图。

    array(3) {
  [0]=>
  array(3) {
    ["ID"]=>
    string(1) "2"
    ["PID"]=>
    NULL
    ["Naam"]=>
    string(7) "Contact"
  }
  [1]=>
  array(3) {
    ["ID"]=>
    string(1) "5"
    ["PID"]=>
    string(1) "2"
    ["Naam"]=>
    string(7) "testing"
  }
  [2]=>
  array(3) {
    ["ID"]=>
    string(1) "6"
    ["PID"]=>
    NULL
    ["Naam"]=>
    string(8) "testing2"
  }
}

如何让数组很好地嵌套? 它看起来应该更像这样:

[0]=>
  array(3) {
    ["ID"]=>
    string(1) "2"
    ["PID"]=>
    NULL
    ["Naam"]=>
    string(7) "Contact"
      'childNodes' => array(
            2 => array(
                ["ID"]=>
                string(1) "5"
                ["PID"]=>
                string(1) "2"
                ["Naam"]=>
                 string(7) "testing"
                'childNodes' => array ();
   );
  }

1 个答案:

答案 0 :(得分:0)

假设这是(某种)你想要的东西:

<?PHP
$entries = array();

$entries[] = array("ID" => "2", "PID" => NULL, "Naam" => "Contact");
$entries[] = array("ID" => "5", "PID" => "2", "Naam" => "testing");
$entries[] = array("ID" => "6", "PID" => NULL, "Naam" => "testing2");

function convertToTree($flat, $idField = 'ID', $parentIdField = 'PID', $childNodesField = 'childNodes', $curIdx = NULL)
{
    $indexed = array();

    foreach($flat as $row)
    {
        if ($row[$parentIdField] == $curIdx)
        {
            $indexed[$row[$idField]] = $row;
            $indexed[$row[$idField]]["childNodes"] = convertToTree($flat, $idField, $parentIdField, $childNodesField, $row[$idField]);
        }
    }

    return $indexed;
}

print_r($entries);
$tree = convertToTree($entries);
print_r($tree);
?>