Search code examples
phparraysirc

Create and manage nested array


I've tried for a while to figure out how to get this to work and after a lot of Google and not being able to find a problem similar to mine (maybe I'm looking for the wrong thing?) I decided to ask:

I've got incoming data that shows essentially a binary tree of IRC server UUIDs, that is the server's UUID and its parent's UUID. What I want to do is create an array that's a tree of this, the incoming data is sort of as follows:

Parent => Child
none => 01D
01D => 01B
01B => 01F
01B => 8OS
01B => 01k
01K => 01M

And I want it to be in an array such as:

$tree = array('01D' => array(
                       '01B' => array(
                                '01F' => array(),
                                '8OS' => array(),
                                '01k' => array('01M' => array()));

I don't get the data all at once, and it's not in a database, so essentially I need to be able to add branches at will.

The primary reason I want to do it this way is in case one of the server disappears, say "01F" I know which children are its and can go through those. So, how would I loop through the children in that regard? Essentially in an IRC context, dealing with netsplits.

I'm not even sure if this is the best way to do this, probably not.


Solution

  • It makes no sense for the incoming data to be in this format:

    Parent => Child
    none => 01D
    01D => 01B
    01B => 01F
    01B => 8OS
    01B => 01k
    01K => 01M
    

    ...because the keys are non-unique (ex. 01B). You should flip the array so it looks like this:

    $uuids = array(
        '01D' => NULL,
        '01B' => '01D',
        '01F' => '01B',
        '8OS' => '01B',
        '01K' => '01B',
        '01M' => '01K'
    );
    

    Finding the children of a failed node is a simple loop and in_array() call:

    $failedNodes = array('01B'); // original failed node
    
    foreach ($uuids as $child => $parent) {
        if (in_array($parent, $failedNodes)) {
            $failedNodes[] = $child;
        }
    }
    
    var_dump($failedNodes);
    

    Output:

    array(4) {
      [0]=>
      string(3) "01B"
      [1]=>
      string(3) "01F"
      [2]=>
      string(3) "8OS"
      [3]=>
      string(3) "01k"
    }