Michael Eugene Yuen Michael Eugene Yuen - 6 months ago 13
SQL Question

LOOP Function return array as NULL while var_dump before return works

I can get the var_dump working for the array but can't get the return function to work. the return value is always NULL. Can anyone help?

EXPECT RESULT:

which I get from var_dump is:

array(3) { [0]=> string(23) "-orange" [1]=> string(22) "-fruit" [2]=> string(22) "-plant" }

CREATE TABLE IF NOT EXISTS `level_test` (
`id` int(11) NOT NULL,
`name` varchar(80) NOT NULL,
`parentid` int(11) NOT NULL
) ENGINE=MyISAM AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;

INSERT INTO `level_test` (`id`, `name`, `parentid`) VALUES
(1, 'plant', 0),
(2, 'fruit', 1),
(3, 'vegetable', 1),
(4, 'apple', 2),
(5, 'orange', 2),
(6, 'tomatoe', 3),
(7, 'cabbage', 3);

ALTER TABLE `level_test`
ADD PRIMARY KEY (`id`);

ALTER TABLE `level_test`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=8;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;


function find_tree($pdcatid, $tree ="") {
global $con;
if ($tree == '') {
$tree = array();
}
$query_level = "SELECT * from level_test WHERE `id` = $pdcatid";
if ($result = $con->query($query_level)) {
while($row = $result->fetch_array()) {
if ($result->num_rows == 1) {
array_push($tree, '-<a href="'.$row['id'].'">'.$row['name'].'</a>');
if ($row['parentid'] == 0) {
var_dump($tree); // this works
return $tree; // this doesn't
echo 'hello'; // just for troubleshoot which it doesn't echo
} else {
$parentid = $row['parentid'];
find_tree($parentid, $tree);
}
}
}
}
}

$result_tree = find_tree(5);
var_dump($result_tree);

Answer

return recursive find_tree result like this:

if ($row['parentid'] == 0) {
    var_dump($tree); // this works
    return $tree; // this doesn't
    echo 'hello'; // just for troubleshoot which it doesn't echo
} else {
    $parentid = $row['parentid'];
    return find_tree($parentid, $tree); // <-- HERE
}

Now, you return value only if $row['parentID'] is 0. If parentID is not 0, you nothing return (NULL). All void function return NULL. Then, if you call non-void function recursive you must return its result in parent call.