PHP: Convert
  • Tree HTML tag to an array

后端 未结 4 1021
无人共我
无人共我 2021-01-16 10:53

I\'m using jsTree and I need to convert this HTML tag tree code

  • to a PHP array. The jsTree HTML tag will be passed to PHP to be parsed and
4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-16 11:29

    Instead of messing with html you should submit the tree data in a more programmer-friendly format.

    $('#saveButton').click(function() {
        var treeData = $.tree.reference($('#sortableTree')).get(undefined, 'json');
        var tmp = serializeTree(treeData, 0);
        // now json-encode tmp and submit it
    });
    
    function serializeTree(nodes, parent)
    {
        var parents = {};
        var childOrder = []
        var childOrders = {};
        for(var i = 0; i < nodes.length; i++)
        {
            var node = nodes[i];
            var id = node.attributes.id.substr(5); // assuming the id looks like 'abcd-ID'
            parents[id] = parent;
            childOrder.push(id);
            if(node.children)
            {
                var tmp = serializeTree(node.children, id);
                for(var id in tmp[0])
                    parents[id] = tmp[0][id];
                for(var id in tmp[1])
                    childOrders[id] = tmp[1][id]
            }
        }
    
        childOrders[parent] = childOrder;
    
        return [parents, childOrders];
    }
    

提交回复
热议问题