I want to make my flat array to a nested array but I can't seem to do this ;/
the code that I tryed to make it nested with:
<?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);
?>
the array it gives out. it clearly doesn't do what I intended for.
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"
}
}
How do i get the array to be nested nicely? it should look more like this:
[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 ();
);
}
it clearly doesn't do what I intended for.What you have there is a nested array. If it isn't what you want, then you need to tell us exactly how the resulting array should look.