LinuxQuestions.org
Did you know LQ has a Linux Hardware Compatibility List?
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices



Reply
 
Search this Thread
Old 01-09-2012, 07:33 PM   #1
wh33t
Member
 
Registered: Oct 2003
Location: Canada
Distribution: Ubuntu Server LTS 14.04.1
Posts: 472

Rep: Reputation: 34
Angry PHP - Return Array from a Function issues... GRR!


Hey guys, can anyone tell me what is going wrong with this script?

Code:
//This function retrieves all of the parents of a category
function category_family($category_id)
{
  
  global $parent_category_array;
  
  //Select the child category that we want to retrieve the parents for
  $query = 'select * from item_categories where item_category_id = "' . $category_id . '"';
  $result = mysql_query($query);
  $a_parent_category = mysql_fetch_assoc($result);
  
  //If we found a parent category
  if(is_array($a_parent_category))
  {
    
    echo 'Found [' . $a_parent_category['item_category_name'] . ']<br />';
    
    //Record it.
    $parent_category_array[] = $a_parent_category;
    
    //Check again to see if we will find another (recursively call itself again until no more have been found)
    category_family($a_parent_category['item_category_parent']);
    
  } else { //If we didn't managed to find a parent category
    
    //Even though we didn't find a parent category this time, it's possible we found one before
    if(is_array($parent_category_array))
    {
      
      echo 'Exiting with an array';
      
      //If we found at least one category, return the array.
      return $parent_category_array;
      
    } else {
      
      echo 'Exiting with out an Array';
      
      //If we never found one category ever, just return false.
      return false;
      
    }
    
  }
  
}

//Load all of the parents
$parents = category_family(2907);

print_r($parents);
The output of this script is as follows.

Quote:
Found [Sub Sub Category]
Found [Sub Category]
Found [Main Category]
Exiting with an array.
Ok, so what I'm gathering is that the function is indeed locating parent categories. That it is exiting while it knows that it's found parent categories yet for some reason I am unable to retrieve the category array from the function when I try to create an array called "$parents" ($parents = category_family(2907)

What the HELL am I missing here?

Last edited by wh33t; 01-11-2012 at 05:53 PM. Reason: SOLVED !
 
Old 01-10-2012, 05:04 AM   #2
Snark1994
Senior Member
 
Registered: Sep 2010
Location: Wales, UK
Distribution: Arch
Posts: 1,632
Blog Entries: 3

Rep: Reputation: 345Reputation: 345Reputation: 345Reputation: 345
I dunno if this is the issue, but you're certainly mixing global variables with local ones (local ones being preferred). What happens if you add
Code:
print_r($parent_category_array);
?

I would be more happy if each time you returned from category_family() you returned an array or false (which you do) but then didn't update the $parent_category_array at all.

You would just call

Code:
return array_merge(category_family(blah),$a_parent_category);
when returning (or similar, I'm at school so can't check code )

Hope this helps,
 
Old 01-10-2012, 10:21 AM   #3
heinblöd
Member
 
Registered: May 2004
Location: France
Distribution: Slackware Gentoo
Posts: 186

Rep: Reputation: 31
just had a quick look , but I would say that your condition

Code:
if(is_array($parent_category_array))
will always be true even when you don't get a result from the SQl
as you declared an empty array before
 
Old 01-11-2012, 12:07 AM   #4
wh33t
Member
 
Registered: Oct 2003
Location: Canada
Distribution: Ubuntu Server LTS 14.04.1
Posts: 472

Original Poster
Rep: Reputation: 34
Hey guys, I appreciate the replies. I have since altered the script to further investigate where I'm going wrong here. Here is the new code.

Code:
//This function retrieves all of the parents of a category
function category_family($category_id)
{
  
  global $parent_category_array;
  
  //Select the child category that we want to retrieve the parents for
  $query = 'select * from item_categories where item_category_id = "' . $category_id . '"';
  $result = mysql_query($query);
  $a_parent_category = mysql_fetch_assoc($result);
  
  //If we found a parent category
  if(is_array($a_parent_category))
  {
    
    echo 'Found [' . $a_parent_category['item_category_name'] . ']<br />';
    
    //Record it.
    $parent_category_array[] = $a_parent_category;
    
    //Check again to see if we will find another (recursively call itself again until no more have been found)
    category_family($a_parent_category['item_category_parent']);
    
  } else { //If we didn't managed to find a parent category
    
    //Even though we didn't find a parent category this time, it's possible we found one before
    if(is_array($parent_category_array))
    {
      
      echo 'This is the Array being echo`d from the function.<br />';
      
      print_r($parent_category_array);
      
      //If we found at least one category, return the array.
      return $parent_category_array;
      
    } else {
      
      echo 'Exiting with out an Array<br />';
      
      //If we never found one category ever, just return false.
      return false;
      
    }
    
  }
  
}

//Load all of the parents
$parents = category_family(2907);

echo '<br />This is the Array being echo`d from outside of the function.<br />';

print_r($parents);
This is it's output now.

Quote:
Found [Sub Sub Category]
Found [Sub Category]
Found [Main Category]
This is the Array being echo`d from the function.
Array ( [0] => Array ( [item_category_id] => 2907 [item_type_id] => 1 [item_category_name] => Sub Sub Category [item_category_desc] => [item_category_parent] => 2906 [item_category_order] => 0 [date_created] => 1326071099 ) [1] => Array ( [item_category_id] => 2906 [item_type_id] => 1 [item_category_name] => Sub Category [item_category_desc] => [item_category_parent] => 2767 [item_category_order] => 0 [date_created] => 1326071092 ) [2] => Array ( [item_category_id] => 2767 [item_type_id] => 1 [item_category_name] => Main Category [item_category_desc] => Here is a description. [item_category_parent] => 0 [item_category_order] => 1 [date_created] => 1312659389 ) )
This is the Array being echo`d from outside of the function.
So from what I gather. EVERYTHING is working as I expect it to. The function is calling itself recursively as it should. When it fails to find any more Parent Categories it is exiting the function EXACTLY where I expect it too. "This is the Array being echo`d from the function." is running from:

Code:
echo 'This is the Array being echo`d from the function.<br />';
      
print_r($parent_category_array);
      
//If we found at least one category, return the array.
return $parent_category_array;
I also notice it is indeed printing out the $parent_category_array right in the exit statement. The problem appears to be with returning it! GRR! What is going on! Is that not how you return an array from a function? Shouldn't this work:

Code:
function make_an_array()
{
  $array_name[0] = 'some value';
  $array_name[1] = 'some other value';

  return $array_name;
}

$new_array_from_a_function = make_an_array();
 
Old 01-11-2012, 01:24 AM   #5
Nominal Animal
Senior Member
 
Registered: Dec 2010
Location: Finland
Distribution: Xubuntu, CentOS, LFS
Posts: 1,723
Blog Entries: 3

Rep: Reputation: 943Reputation: 943Reputation: 943Reputation: 943Reputation: 943Reputation: 943Reputation: 943Reputation: 943
Quote:
Originally Posted by wh33t View Post
Code:
category_family($a_parent_category['item_category_parent']);
When you do the above recursive call, you discard the return value!

So, if you have nested results (and you do), the very first recursive call will just drop the results on the floor and return nothing. Note that after that call no return statement will be executed.

Consider this recursive example.
Code:
function babushka($depth, $array = FALSE)
{
    if ($depth > 1)
        $array = babushka($depth - 1, $array);

    if ($array === FALSE || $array === NULL)
        $array = array();
    else
    if (!is_array($array))
        $array = array( $array );

    return array( 'depth' => $depth, 'array' => $array );
}

var_dump(babushka(1));
var_dump(babushka(5, array("One", "Two"));
var_dump(babushka(4, babushka(3, babushka(2, array("1", "0")))));
Your make_an_array() example function does work, if you first initialize $array_name to an empty array, i.e.
Code:
function make_an_array()
{
  $array_name = array();
  $array_name[0] = 'some value';
  $array_name[1] = 'some other value';
  return $array_name;
}
although a much simpler way to write the same function would be
Code:
function make_an_array()
{
  return array( 0 => 'some value',
                1 => 'some other value' );
}
Hope this helps.
 
Old 01-11-2012, 02:42 AM   #6
wh33t
Member
 
Registered: Oct 2003
Location: Canada
Distribution: Ubuntu Server LTS 14.04.1
Posts: 472

Original Poster
Rep: Reputation: 34
I get it now. Thanks for your help man.

The problem is that I was assuming that when I recursive called the function that it wouldn't run any more statements after.

This now works as expected.

PHP Code:
//This function retrieves all of the parents of a category
        
function category_family($category_id)
        {
          
          global 
$parent_category_array$run_times;
          
          
//Select the child category that we want to retrieve the parents for
          
$query 'select * from item_categories where item_category_id = "' $category_id '"';
          
$result mysql_query($query);
          
$a_parent_category mysql_fetch_assoc($result);
          
          
$run_times++;
          
          
//If we found a parent category
          
if(is_array($a_parent_category))
          {
            
            
//Record it.
            
$parent_category_array[] = $a_parent_category;
            
            
//Check again to see if we will find another (recursively call itself again until no more have been found)
            
category_family($a_parent_category['item_category_parent']);
            
            return 
$parent_category_array;
                        
          } else { 
//If we didn't managed to find a parent category
            
            //If we didn't find a parent.
            
return false;
            
          }
          
        }
        
        
//Load all of the parents
        
$parents category_family(2907);

        
print_r($parents); 
 
Old 01-11-2012, 11:48 AM   #7
Snark1994
Senior Member
 
Registered: Sep 2010
Location: Wales, UK
Distribution: Arch
Posts: 1,632
Blog Entries: 3

Rep: Reputation: 345Reputation: 345Reputation: 345Reputation: 345
Well done, if you don't have any further questions can you mark this thread as SOLVED please? (and mark e.g. Nominal Animal's post as being 'helpful', as I'm guessing it probably was )

Thanks,
 
1 members found this post helpful.
Old 01-11-2012, 05:52 PM   #8
wh33t
Member
 
Registered: Oct 2003
Location: Canada
Distribution: Ubuntu Server LTS 14.04.1
Posts: 472

Original Poster
Rep: Reputation: 34
Will do. Thank you LQ!
 
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
how to return array from function c++ vbx_wx Programming 3 11-09-2010 05:21 PM
php mysql array return trscookie Programming 6 11-08-2010 08:18 PM
C return array of structures from function j0hnsmith Programming 11 05-11-2009 09:26 AM
PHP Function to return the most recent error. id10t Programming 5 05-30-2004 07:24 PM
function won ' t return character array word Linh Programming 1 07-31-2003 07:11 PM


All times are GMT -5. The time now is 09:53 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
identi.ca: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration