Search code examples
phparraysrecursionparents

php recursive get parents


I am trying to get jquery.treeview.js to fold out to the just created folder. Think I need an array of "parents" to set class to "open".

Other suggestions works with me ;-) (find this a bit too much but cannot find another way to do it.

Having an array like this:

    array(7) {
      [126]=>
      array(4) {
        ["folder_id"]=>
        string(3) "126"
        ["folder_name"]=>
        string(3) "555"
        ["folder_parent"]=>
        string(3) "125"
      }
      [2]=>
      array(4) {
        ["folder_id"]=>
        string(1) "2"
        ["folder_name"]=>
        string(14) "Administration"
        ["folder_parent"]=>
        string(1) "1"
      }
      [7]=>
      array(4) {
        ["folder_id"]=>
        string(1) "7"
        ["folder_name"]=>
        string(5) "Britt"
        ["folder_parent"]=>
        string(1) "2"
      }
      [4]=>
      array(4) {
        ["folder_id"]=>
        string(1) "4"
        ["folder_name"]=>
        string(9) "Documents"
        ["folder_parent"]=>
        string(1) "3"
      }
      [3]=>
      array(4) {
        ["folder_id"]=>
        string(1) "3"
        ["folder_name"]=>
        string(14) "Infrastructure"
        ["folder_parent"]=>
        string(1) "1"
      }
      [1]=>
      array(4) {
        ["folder_id"]=>
        string(1) "1"
        ["folder_name"]=>
        string(4) "root"
        ["folder_parent"]=>
        string(1) "0"
      }
      [125]=>
      array(4) {
        ["folder_id"]=>
        string(3) "125"
        ["folder_name"]=>
        string(13) "test-deleteme"
        ["folder_parent"]=>
        string(1) "7"
      }
    }

I would like to get the parents from selected folder_id.

getting data for folder_id=126 should return an array with parents {1,2,7,122}

Anyone?


Solution

  • Well, here is mine with recursive:

    function getParent($folder_id, $data, $parents=array()) {
        $parent_id = isset($data[$folder_id]) ? $data[$folder_id]['folder_parent'] : 0;
        if ($parent_id > 0) {
            array_unshift($parents, $parent_id);
            return getParent($parent_id, $data, $parents);
        }
        return $parents;
    }
    
    //Usage
    print_r(getParent(126, $your_folders));
    

    It seems like I had plagiarized mancuernita's solution I hereby apologize. It's just similar, but I'm not copying!