Jump to content

Return array from function


rcouser

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.