简体   繁体   中英

How to recursively loop through json to create parent/child objects PHP

I have a json file that has an array called "dialogue_nodes". Each object in the array has a "parent" value and a "dialogue_node" value. If a dialogue node has a value for parent, the value references another dialogue node's "dialogue_node" value. In the json file, all of the parent and child nodes are on the same "level" in the top dialogue_nodes array. I'm currently manually looping through the array.

How do I dynamically loop through the array to account for the indefinite levels of the parent/child relationships? Here is my current code.

$content = file_get_contents( "testWorkspace.json" );

$json = json_decode( $content );
$dialogueNodes = $json->dialog_nodes;

foreach ( $dialogueNodes as $node ) {

   if ( !isset( $node->parent ) ) {

       $topNodes[] = $node;

   } else {

    $otherNodes[] = $node;
   }
}

foreach ( $topNodes as $node ) {

   echo "top: {$node->title}";

   foreach ( $otherNodes as $node2 ) {

    if ( $node2->parent == $node->dialog_node ) {

        echo "level 2 child is {$node2->dialog_node} {$node2->title}";

        foreach ( $otherNodes as $node3 ) {

            if ( $node3->parent == $node2->dialog_node ) {

                echo "level 3 child is {$node3->dialog_node} {$node3->title}";

 continues.....

Here is a sample input. The first object is a parent node example, the second is a child node

{
  "title": "Welcome",
  "dialog_node": "node_5_1550586774524",
},
{
  "condition": true
  "output": "hello"
  "parent": "node_5_1550586774524"
  "dialog_node": "node_12_1554909604222"
},

You might be looking for a recursive function like:

foreach($topNodes as $node) {
  echo "top: {$node->title}";
  recursiveFunction($otherNodes, 1, $node->dialog_node);
}
function recursiveFunction($nodes, $level, $parent = null) {
  $level++;
  foreach($nodes as $node) {
    if ($node->parent === $parent ) {
      echo "level $level child is {$node->dialog_node} {$node->title}";
      recursiveFunction($nodes, $level, $node->dialog_node);
    }
  }
}

But be very careful: recursive functions might be dangerous and end up in infinite loops.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM