0

I am trying to find out the parents of a new member till root. For this, I have written a recursive function in PHP that is expected to work, but results are not as expected.

$parlist=array();
function parlistf($child, $con, &$parlist)
{
 $qry="SELECT par from users where sno='$child'";
 $res=$con->query($qry);
 $row=$res->fetch_object();
 if($row->par>0)
 {
    echo "<br>-----<br>$row->par<br>-----<br>";
    $parlist[] = parlistf($row->par, $con, $parlist);;
    var_dump($parlist);
 }
}
parlistf($newid, $con, $parlist);
echo "<br>";
var_dump($parlist);

Result of above code is as under:

-----
15
-----

-----
7
-----

-----
3
-----

-----
1
-----
array(1) { [0]=> NULL } array(2) { [0]=> NULL [1]=> NULL } array(3) { [0]=> NULL [1]=> NULL [2]=> NULL } array(4) { [0]=> NULL [1]=> NULL [2]=> NULL [3]=> NULL } array(4) { [0]=> NULL [1]=> NULL [2]=> NULL [3]=> NULL }

As your can see here, echo is working fine but values are not stored in the array. Where I am doing wrong?

2
  • $parlist[] = parlistf($row->par, $con, $parlist);; has two ; and I dont see what return it is feeding the array. Commented Jan 9, 2018 at 17:54
  • 1
    @NappingRabbit - pass by reference. &$parlist Commented Jan 9, 2018 at 17:55

1 Answer 1

2

Try this:

$parlist[] = $row->par;
parlistf($row->par, $con, $parlist);

instead of this:

$parlist[] = parlistf($row->par, $con, $parlist);

Your line feeds $parlist with the not existing return value of the function.

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

5 Comments

I forgot a column in sql query: SELECT par, lvl from users where sno='$child' How can I store both as pair in associative array?
Depending on what output you need, it could be $parlist[$row->par] = $row->lvl; or $parlist[] = [$row->par=>$row->lvl];
var_dump($parlist); now shows: array(4) { [0]=> array(1) { [15]=> int(3) } [1]=> array(1) { [7]=> int(2) } [2]=> array(1) { [3]=> int(1) } [3]=> array(1) { [1]=> int(0) } } But, looping as: foreach($parlist AS $id=>$xlvl) { $elvl=$lvl-$xlvl; } says: Fatal error: Unsupported operand types
$xlvl contains an array in your example
if this right approach: for($i=0; $i<count($parlist); $i++) { foreach($parlist[$i] as $id=>$xlvl) { $elvl=$lvl-$xlvl;}}

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.