0

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 ();
   );
  }
1
  • 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. Commented Jan 9, 2014 at 13:55

2 Answers 2

1

Suppose this is (kind of) what you want:

<?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);
?>
Sign up to request clarification or add additional context in comments.

1 Comment

@user2013498 If this solves your problem, please accept the answer by clicking the tick to the left of the answer.
0
/**
 * Transform array to a nested structure.
 * This gets a little complicated. Basically, we're creating a placeholder in
 * $children to hold the child terms of each parent term. Then we create a
 * reference to that element in the parent term. So nesting happens via magic.
 */
function arrayFlatToNested($array, $idKey = 'ID', $parentIdKey = 'PID', $childrenKey = 'childNodes'): array
{
    $arrayNested = [];
    $children = [];

    foreach ($array as $element) {
        // Create a placeholder for the object's children.
        if (!isset($children[$element[$idKey]])) {
            $children[$element[$idKey]] = [];
        }
        // Create a link to those children.
        $element[$childrenKey] = &$children[$element[$idKey]];

        if (!strlen($element[$parentIdKey])) {
            $arrayNested[] = $element;
        } else {
            // Create a placeholder for the parent.
            if (!isset($children[$element[$parentIdKey]])) {
                $children[$element[$parentIdKey]] = [];
            }
            // Add this object to the parent, even if it doesn't exist yet.
            $children[$element[$parentIdKey]][] = $element;
        }
    }

    return $arrayNested;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.