整晚都在打架。放弃。我在mysql中有一个相邻的表:
id, parentid,name,design,path,sort
深度最大为4,使用mysql查询,我将结果打印成UL列表成功。从那里,项目被添加,排序和编辑以及删除。然后当单击按钮时,我将结果发送回php。发送的数据是JSON,它确实收到了。
json_decode()
提供以下示例:
Array ( [0] => Array ( [cls] => [path] => # [id] => 1 [name] =>BLOCKA ) [1] => Array ( [cls] => [path] => # [id] => 2 [name] => BLOCKB [children] => Array ( [0] => Array ( [cls] => [path] => # [id] => 3 [name] => CLASSB1 [children] => Array ( [0] => Array ( [cls] => [path] => # [id] => 7 [name] => CLASSB12 ) ) ) [1] => Array ( [cls] => [path] => # [id] => 4 [name] => CLASSSB13 [children] => Array ( [0] => Array ( [cls] => [path] => # [id] => 5 [name] => CLASSB4 ) [1] => Array ( [cls] => [path] => # [id] => 6 [name] => CLASSB5 ) ) ) ) ) )
图形:
BLOCKA
BLOCKB
CLASSB1
CLASSB3
...
我正在使用jquery.nested
现在我的问题是循环遍历数组,获取父级的id然后添加子级。
我最亲近的是
function dissect($blocks) {
if (!is_array($blocks)) {
echo $blocks;
return;
}
foreach($blocks as $block) {
dissect($block);
}
}
它会处理每个元素,但不会按照我想要的方式处理。对不起,我的英语很糟糕...任何帮助都将不胜感激。
答案 0 :(得分:0)
首先遍历获取父级的块,如果父级块中存在子级,则遍历子级。
可能还有其他更好的方法来实现这一点,您可以尝试下面的代码:
//#1 Use the dict to iterate through them
foreach (KeyValuePair<string, Rectangle> rect in rectangleDict)
{
Console.WriteLine(rect.Key);
//iterate through any property in the rectangle such as its sides, name, etc
Console.WriteLine(rect.Value.name);
}
//#2 use the key directly to access a property
Console.WriteLine(rectangleDict["rectangle1"].name);
输出:
$blocks = array (
"0" => array (
"cls" => "",
"path" => array(
"id" => 1,
"name" =>"BLOCKA",
)
),
"1" => array (
"cls" => "",
"path" => array(
"id" => 2,
"name" => "BLOCKB" ,
"children" => array (
"0" => array (
"cls" => "",
"path" => array(
"id" => 3,
"name" => "CLASSB1" ,
"children" => array (
"0" => array (
"cls" => "",
"path" => array(
"id" => 7,
"name" => "CLASSB12" ,
),
),
),
),
),
"1" => array (
"cls" => "",
"path" => array(
"id" => 4,
"name" => "CLASSSB13" ,
"children" => array (
"0" => array (
"cls" => "",
"path" => array(
"id" => 5,
"name" => "CLASSB4" ,
),
),
"1" => array (
"cls" => "",
"path" => array(
"id" => 6,
"name" => "CLASSB5",
),
),
),
),
),
),
),
),
) ;
echo "<pre>";
/*loop through blocks*/
foreach ($blocks as $key => $block) {
echo $block['path']['name'].'<br/>'; /* echo parent*/
if (isset($block['path']['children'])) {
loopChildren($block['path']['children']); /* children loop*/
}
}
/*Loop through childrens*/
function loopChildren($childrens, $prefix = '-')
{
foreach ($childrens as $key => $child) {
getChild($child, $prefix);
}
}
/*Get the child and loop sub-children if exist*/
function getChild($child, $prefix='-')
{
echo $prefix. $child['path']['name'].'<br/>'; /*echo child*/
if (isset($child['path']['children'])) {
$prefix .= '-';
loopChildren($child['path']['children'], $prefix); /* sub-children loop*/
}
}
echo "</pre>";
答案 1 :(得分:0)
感谢您的提示。它引导我找到一个对我有用的答案。我最终使用了两个功能。错误是“索引越界”......这是我现在所做的...调用mysql表:
SystemError