Jump to content

adding to an array with each recursive function


1internet

Recommended Posts

I want to add to an array when each recursive function is called. I have played around with it a few ways, but just getting error after error. This is about where I am up to, it should be enough to work out what I am trying to accomplish.

function structure($x, $structure = array()) {
$qry = mysql_query("SELECT `parent_id` FROM `categories` WHERE `categories_id`=$x");
$result = mysql_fetch_assoc($qry);
$cat = $result['parent_id'];
if($cat !=0) {
structure($cat, $structure[] = $cat);
}
echo $cat.' >';
return $structure;
}

echo structure(22);
var_dump($structure);

So I am also trying to return the array as well, unsuccessfully. I am not sure how you return an array from a function either.

So I would appreciate help on how to add to an array with each recursive function and return the array outside of the function into a useable variable.

Link to comment
Share on other sites

Since you are modifying the array inside the function and expecting that change to be available to the code that calls the function (recursively), you must pass the array by reference:

function structure($x, &$structure = array()) {

 

However, I think that would mean you have to pass an empty array in your initial call (I'm not sure, maybe not - I'm not real clear on omitting a reference parameter):

$result = array();
structure(22, $result);
var_dump($result);
You are returning the array correctly from the function, but you are not capturing the returned value in the initial call. Also, you cannot echo an array.

$structure = structure(22);
var_dump($structure);
Note: Avoid using the same name for a function as you use for a variable. It makes the code confusing: echo structure(22); Is that supposed to be echo $structure[22];? I generally try to use a verb phrase for functions (they perform actions) and a noun for variables (they name a thing). So $structure and buildStructure().
Link to comment
Share on other sites

Look in to variable scoping.  The array outside your function has one structure and the array inside your function another.  Also, check out PDO or mysqli instead of mysql_.  Here's you code:

<?php
define("DB_HOST", "localhost");
define("DB_NAME", "databasename");
define("DB_UNAME", "dbusername");
define("DB_UPWORD", "dbuserpassword");
$structure = array();
$x = array(22,23);
print_r($x);

try{
		$_conn = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME.'', DB_UNAME, DB_UPWORD);
	} catch (PDOException $e){
		print "Error: ".$e->getMessage()."<br>";
		die();
	}
	

function runStructure($value, $_conn, $array) {

  $query = "SELECT `parent_id` FROM `categories` WHERE `categories_id`=?";

  $stmt = $_conn->prepare($query);
  $stmt->bindParam(1,$value);
  $stmt->execute();
  $row=$stmt->fetch(PDO::FETCH_ASSOC);
  $array[]=$row['parent_id'];
  //echo $row['parent_id'];
  return $array;
}

foreach($x as $k=>$v) {
  $structure = runStructure($v,$_conn,$structure);
}

print_r($structure);
?>

Couple things to note.  The database connection is outside the function.  This way you only have one db connection.  Two, the $x variable should be an array of all your id you want to query.  Finally, you see at the bottom, I'm looping through each $x array element and calling the function on the individual nodes.  This code block works here:

 

Try it out.

Link to comment
Share on other sites

Thanks, that seemed a bit better, but still getting an error:

 

Fatal error: Call-time pass-by-reference has been removed in C:\xampp\htdocs\customers\msl\test-nav3.php on line 23

I'm not sure what line 23 is, since you did not post your new code. But that error comes from a change in PHP. To pass a variable by reference, you used to use:

$result = myFunction(&$varByReference); # See the "&" in the call to the function

 

The "&" in the call is no longer needed. If the function is defined to accept a parameter by reference, any call to it will be by reference. So:

function myFunction(&$paramByReference) {
  // Do something
}

$varByReference = null; # Or whatever value you want to start with
$result = myFunction($varByReference); # Note NO "&" in the call

$result = myFunction(&$varByReference); # This line produces that error
Link to comment
Share on other sites

Here's a simple example of a recursive function writing to an array

$results = array();

function gatherResults($var, &$results) {
    $results[] = $var;
    if ($var >= 10) return; // terminate the recursion
    gatherResults($var+1, $results);
}

$var = 1;
gatherResults($var, $results);

echo '<pre>',print_r($results, true),'</pre>';
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.