[英]How to recursively loop through json to create parent/child objects PHP
I have a json file that has an array called "dialogue_nodes". 我有一个json文件,有一个名为“dialogue_nodes”的数组。 Each object in the array has a "parent" value and a "dialogue_node" value.
数组中的每个对象都有一个“父”值和一个“dialog_node”值。 If a dialogue node has a value for parent, the value references another dialogue node's "dialogue_node" value.
如果对话节点具有父值,则该值引用另一个对话节点的“dialogue_node”值。 In the json file, all of the parent and child nodes are on the same "level" in the top dialogue_nodes array.
在json文件中,所有父节点和子节点都位于顶部的dialog_nodes数组中的相同“级别”。 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. 但要非常小心:递归函数可能很危险,最终会出现无限循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.