1

I am using codeIgniter. I need to create a multidimensional array of the data from the DB nammed college. The database has 3 columns: id, OfID and name. The OfID column contains the ID of the parent of that college. For colleges who don't have any parent have OfID as 0.

The array should contain the name, ID and OfID of colleges who have OfID=0 as the elements of first dimension. For colleges which have OfID!=0 should be put as 2nd (and so on) dimension array for the college whose ID they have as OfID.

I thought to do this recursively , but I am unable to finish this. I know there are a lot of mistakes in this please help.

The model class follows: (the controller calls meth() function)

class Model extends CI_Model
{
var $return_this=array();
function meth()
{       
    $loop_id=0;
    getit($loop_id);
    var_dump($return_this);
}
function getit($loop_id)
{
    $index=0;
    $query = $this->db->query("select * from college where OfID=$loop_id ORDER BY `OfID` ASC;");
    if ($query->num_rows() > 0)
    {
        foreach ($query->result() as $row)
        {
            $pass=$row->id;
            $temp=getit($pass);
            if($temp==0)
            $return_this[$loop_id]= $query->result();
        }
    }
    else return 0;
}

}
1
  • The mistake was not using $this keyword. Commented Jul 2, 2012 at 7:37

1 Answer 1

1

Try something like this:

$rows = array();
foreach ($query->result() as $row)
    {
        $pass=$row->id;
        $rows[] = getit($pass);
    }
return $rows;

In any case, the best way I found myself to do recursion, is to take some recursive function that is really simple and you know every aspect about it, and to build it up step by step. By "step by step" I mean at first you don't pass all the values, but print them out, just to see what, where and how you get, then try to pass them. Recursive functions such as this one are brain damaging if you don't understand how it works. The idea behind your one, is to get an array every time you stumble upon a college that has child colleges. I can see you get it right, just try to make this one as I told earlier - step by step and you will get a hang of it.

Sign up to request clarification or add additional context in comments.

1 Comment

The mistake was not using $this keyword.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.