Sandi Horvat Sandi Horvat - 8 months ago 64
PHP Question

Create an adjacency structure from a list of sequence

I would like to build an Adjacency List from my list of sequence in a php. The thing is, that my list of sequince is in array and it looks like this:

$arr = array("1", "1.1", "1.2", "2", "2.1", "2.1.1", "2.1.2");

Now, I would like to transform it so that it would be in a Adjanency list model, like this:

$arr1 = array("0", "1", "1", "0", "4", "5", "5");

So, my $arr1 will be representing a 'parentId' in the table for a tree view(jsTree).

Can please somebody point me to the right directon, or where should I start looking for a solution.

Thank you.


You could do something like this:

for ($i = 0; $i < count($arr); $i++) {
    $splitString = explode(',', $arr[i]); //split the string on the point
    if (strlen($splitString) > 1) {
        $arr1[i] = $splitString[1]; // take the part after the point
    else {
        $arr1[i] = "0"; // no part after the point, so default to 0