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?

asked Jan 9, 2018 at 17:52
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.

answered Jan 9, 2018 at 17:57
5
  • 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? Commented Jan 9, 2018 at 18:06
  • Depending on what output you need, it could be $parlist[$row->par] = $row->lvl; or $parlist[] = [$row->par=>$row->lvl]; Commented Jan 9, 2018 at 18:16
  • 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 Commented Jan 9, 2018 at 18:42
  • $xlvl contains an array in your example Commented Jan 9, 2018 at 18:48
  • if this right approach: for($i=0; $i<count($parlist); $i++) { foreach($parlist[$i] as $id=>$xlvl) { $elvl=$lvl-$xlvl;}} Commented Jan 9, 2018 at 18:53

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.