关联数组(JSON)到嵌套集(需要左,右值)

时间:2013-08-13 09:52:33

标签: php multidimensional-array nested-sets

所以我有一个关联数组,它已经通过JQuery传递到我的PHP页面,其中包含菜单的结构。这实际上是这样的:

[{"id":1,"children":[{"id":2,"children":[{"id":3},{"id":4}]},{"id":5}]}]

我已经解码了字符串并使用json_decode将其转换为关联数组,如下所示:

$cleanJSON = json_decode($JSON,true);

到目前为止,这一切都很好,结果如下:

Array (
            [0] => Array
                (
                    [id] => 1
                    [children] => Array
                        (
                            [0] => Array
                                (
                                    [id] => 2
                                    [children] => Array
                                        (
                                            [0] => Array
                                                (
                                                    [id] => 3
                                                )
                                            [1] => Array
                                                (
                                                    [id] => 4
                                                )
                                        )
                                )
                            [1] => Array
                                (
                                    [id] => 5
                                )
                        )
                )
        )

我遇到的问题是我现在需要弄清楚每个项目的左右嵌套设置值,以便我可以使用这个新结构更新我的数据库。

我这样做的原因是允许我在嵌套集模型中完成重新排序菜单项。

获得一个类似于下面例子的结果数组将是完美的:

Array (
        [0] => Array
            (
                [id] => 1
                [left] => 1
                [right] => 10
            )
        [1] => Array
            (
                [id] => 2
                [left] => 2
                [right] => 7
            )
        [2] => Array
            (
                [id] => 3
                [left] => 3
                [right] => 4
            )
        [3] => Array
            (
                [id] => 4
                [left] => 5
                [right] => 6
            )
        [4] => Array
            (
                [id] => 5
                [left] => 8
                [right] => 9
            )
    )

下面的代码是乱七八糟的,根本不起作用,但就我所说的而言:

$i_count = 1;
$i_index = 1;
$a_newTree;

function recurseTree($nestedSet) 
{
    global $i_count;
    global $a_newTree;

    $i_left = $i_count;
    $a_newTree[$i_count-1]['left'] = $i_left;
    $i_count++;

    foreach ($nestedSet AS $key => $value)  
    {               
        if ($value['children']) 
          {
              foreach($value['children'] as $a_child)  
              {
                  recurseTree($a_child);      // traverse
              }
          }
    }   

    $i_right=$i_count; // right = count
    $a_newTree[$i_count-1]['right'] = $i_right; 
        $i_count++;        // count+1   
}

任何帮助表示赞赏!

2 个答案:

答案 0 :(得分:2)

<强>解决!

朋友创造的一个漂亮的小功能为我解决了这个问题。他实际上是用Javascript创建的,但我把它翻译成了PHP。我将在下面提供。

首先是PHP版本:

$JSON = '[{"id":1,"children":[{"id":2,"children":[{"id":3},{"id":4}]},{"id":5}]}]';
$cleanJSON = json_decode($JSON,true);

$a_newTree = array();       

function recurseTree($structure,$previousLeft) 
{
    global $a_newTree;  // Get global Variable to store results in.

    $indexed = array();                     // Bucket of results.       
    $indexed['id'] = $structure['id'];      // Set ID
    $indexed['left'] = $previousLeft + 1;   // Set Left

    $lastRight = $indexed['left'];

    $i_count = 0;
    if ($structure['children'])
    {
        foreach ($structure['children'] as $a_child)
        {
            $lastRight = recurseTree($structure['children'][$i_count],$lastRight);
            $i_count++;
        }
    }

    $indexed['right'] = $lastRight + 1;     // Set Right

    array_push($a_newTree,$indexed);        // Push onto stack

    return $indexed['right'];       
}

recurseTree($cleanJSON[0],0);
print_r($a_newTree);

神奇的小功能输出所需的确切数组。

好的,对于我朋友写的原始JAVASCRIPT版本,见下文:

<html>
   <head>
      <title>Experiment</title>
      <script type="text/javascript">
         /* initial structure */
         var struct = [
            {
                "id": 1,
                "children": [{
                    "id": 2,
                    "children": [{
                        "id": 3
                    }, {
                        "id": 4
                    }]
                }, {
                    "id": 5
                }]
            }
         ];

         function experiment() {
            /* stores all results */
            var all = [];

            /* kick off the recursive method */
            handleNode(struct[0], 0, all);

            /* print the results to browser debugger console*/
            console.log(all);
         }

         function handleNode(node, previousLeft, all) {
            /* create and store the new entry (bucket to put left, right, and id ) */
            var indexed = {};
            all.push(indexed);

            indexed.id = node["id"];
            indexed.left = previousLeft + 1;

            var lastRight = indexed.left;
            /* here we do the recursion for every child */
            for (var x in node["children"]) {
               lastRight = handleNode(node["children"][x], lastRight, all);
            }

            /* once all children have been iterated over we can store the rigth */
            indexed.right = lastRight + 1;

            /* return the newly updated right for this bucket */
            return indexed.right;
         }

         /* run the experiment */
         experiment();

      </script>
   </head>
   <body>

   </body>
</html>

使用Google Chrome,您可以在控制台窗口中查看结果。 (CTRL-SHIFT-I)。

答案 1 :(得分:0)

我不会尝试自己编写嵌套集实现,有可用的版本: