Jump to content

Recommended Posts

Hello there,

I am having problem returning array from function the code is as follows:

$category_array = array();
function display_categories($parent, $level) {
$conn = dbConnect('query');
$sql = "SELECT id, name
		FROM categories
		WHERE parent_id = $parent
		AND is_active = 1
		ORDER BY sort_order DESC";
$result = @ $conn->query($sql);
while($categories = $result->fetch_assoc()) {
	$array = array('id' => $categories['id'], 'name' => $categories['name'], 'level' => $level);
	display_categories($categories['id'], $level+1);
}
}
$category_array = display_categories(0,0);
var_dump($category_array);

 

Any help much appreciated.

Thank

Link to comment
https://forums.phpfreaks.com/topic/240205-return-array-from-function/
Share on other sites

Thanks for the reply. I've changed it to the following but it only returns 1 result from the array. Any ideas?

Cheers

$category_array = array();
function display_categories($parent, $level) {
$conn = dbConnect('query');
$sql = "SELECT id, name
		FROM categories
		WHERE parent_id = $parent
		AND is_active = 1
		ORDER BY sort_order DESC";
$result = @ $conn->query($sql);
while($categories = $result->fetch_assoc()) {
	$array[] = array('id' => $categories['id'], 'name' => $categories['name'], 'level' => $level);
	display_categories($categories['id'], $level+1);
	return $array;
}
}
$category_array = display_categories(0,0);
var_dump($category_array);

How would I go about that?

 

Well, that's really part of what you need to figure out during your design phase.  I mean, technically, you just need to assign the function invocation to a variable, like:

 

$var = display_categories($categories['id'], $level+1);

 

Which will capture and place the returned result in $var.

 

That said, you likely won't be getting the value(s) that you want due to the way your function is currently written.  You'd still need to merge them with the $array you return.  On top of that, you'll have to make sure everything lines up during recursion.

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.