I am building a recursive function that traverses a hierarchy in the database until it can not find a parent element.
An example of what can be found in the database is
codeID, codeDescription
1, AB
2, AB.CD
3, AB.CD.EF
4, AB.CD.EF.GH
I start with the codeDescription of AB.CD.EF.GH which is assigned to the $my_string variable.
The following is my code.
function reduceString($string, $information_array = array()) {
//Set up an array to hold the values
$habitat_array = $information_array;
print_r($habitat_array);
echo "<br />";
//Find the last occurence of a period (.) in the string
$position = strrpos($string, ".");
//Remove the end of the string to the final period (.)
$end_string = substr($string, 0, $position);
//Run a query to see if there is a parent element
$new_sql = "SELECT * FROM `codes` WHERE `codeDescription` = '$end_string';";
$new_result = mysql_query($new_sql) or die(mysql_error());
//Check if we have any results
if(mysql_num_rows($new_result) != 0) {
$habitat = mysql_fetch_assoc($new_result);
$habitat_array[$habitat['codeID']] = $habitat['codeDescription'];
//Call the function again
reduceString($end_string, $habitat_array);
} else {
$return_array = $habitat_array;
echo "<p>Return array<br />";
print_r($return_array);
echo "</p>";
}
return(isset($return_array) ? $return_array : false);
}
$my_new_array = reduceString($my_string);
echo "<p>My array from the function</p>";
print_r($my_new_array);
The final line where i print out the contents of $my_new_array comes up blank even though on the final loop through the array is printed out at the beginning containing exactly what I need.
Can anyone point out what I am doing wrong?
Thanks for any help.