Jump to content

adjacency list to xml - additional check


fritzb

Recommended Posts

Hi,

 

I am converting an adjacency table to a xml with this code (coming from phpfreaks, thank you Barand!)

<?php
$data = array(
        1 => 0,
        2 => 1,
        3 => 1,
        4 => 2,
        5 => 3,
        6 => 5
);
echo "<?xml version='1.0' encoding='iso-8859-1'?>\n";
echo "<tree id='0'>\n";
tree(0);
echo "</tree>\n";

function tree ($parent, $level=0)
{
    global $data;
    $children = array_keys($data, $parent);
    if ($children)
    foreach ($children as $kid)
    {
        $indent = str_repeat("\t", $level+1);
        echo "$indent<item text='$kid' id='$kid'>\n";
        tree($kid, $level+1);
        echo "$indent</item>\n";
    }
} 
?>

Returning

<?xml version='1.0' encoding='iso-8859-1'?>
<tree id='0'>
    <item text='1' id='1'>
        <item text='2' id='2'>
            <item text='4' id='4'>
            </item>
        </item>
        <item text='3' id='3'>
            <item text='5' id='5'>
                <item text='6' id='6'>
                </item>
            </item>
        </item>
    </item>
</tree>

Which is inappropriately formatted for my purpose. I would need:

<?xml version='1.0' encoding='iso-8859-1'?>
    <tree id='0'>
        <item text='1' id='1'>
            <item text='2' id='2'>
                <item text='4' id='4'/>
            </item>
            <item text='3' id='3'>
                <item text='5' id='5'>
                    <item text='6' id='6'/>
                </item>
            </item>
        </item>
    </tree>

All nodes with children should end with </item>, leafs without end with />).

 

I included an else-statement, after the foreach, but that obviously only doubles the leafs.

else 
    		{
    		$leaf = $parent;
       		$indent = str_repeat("\t", $level+1);
    		echo "$indent<item text='$leaf' id='$leaf'/>\n";
    		}

Including further if-statements, left me with a completely screwed xml. 

 

Now I run out of ideas how to check for leafs/children and handle them appropriately.  Any help ist appreciated!

 

Link to comment
https://forums.phpfreaks.com/topic/281473-adjacency-list-to-xml-additional-check/
Share on other sites

Better ways to do the whole thing, but here is the easy fix:

    foreach ($children as $kid)
    {
        $indent = str_repeat("\t", $level+1);
        if(in_array($kid, $data)) { //check if this kid is also a parent
            echo "$indent<item text='$kid' id='$kid'>\n";
            tree($kid, $level+1);
            echo "$indent</item>\n";
        } else { //if not then it is the last
            echo "$indent<item text='$kid' id='$kid' />\n";
        }
    }

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.