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
1 Answer 1
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
-
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?ITSagar– ITSagar2018年01月09日 18:06:56 +00:00Commented 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];marcus.kreusch– marcus.kreusch2018年01月09日 18:16:28 +00:00Commented 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 typesITSagar– ITSagar2018年01月09日 18:42:41 +00:00Commented Jan 9, 2018 at 18:42
-
$xlvl contains an array in your examplemarcus.kreusch– marcus.kreusch2018年01月09日 18:48:21 +00:00Commented 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;}}ITSagar– ITSagar2018年01月09日 18:53:32 +00:00Commented Jan 9, 2018 at 18:53
Explore related questions
See similar questions with these tags.
lang-php
$parlist[] = parlistf($row->par, $con, $parlist);;
has two;
and I dont see what return it is feeding the array.&$parlist