hitachitellme
hitachitellme

Reputation: 1

Return array from Recursive - Php

When browsing the binary tree I want to return an array of recursive functions. In particular when an element in binary tree reaching conditions (if statement) is inserted into the array. After all, the element returns an array of all. My code not work !??

function tree_view($clear_static = false,$conn,$index)
{
    static $count = 0;
    if ($clear_static) {
        $count = 0;
    }
    $q=mysql_query("SELECT user_id FROM thanhvien WHERE gioithieu='".$index."'",$conn);

    while($arr=mysql_fetch_assoc($q)) 
    { 
        if (truongban($conn,$arr["user_id"],1)==true){
            $mang[$count]=$arr["user_id"];
            $count++;
        }
        tree_view(false,$conn,$arr["user_id"]); 
    } 
    return $mang;
} 
$mang1=tree_view (true,$conn,anloc);
print_r($mang1);

Upvotes: 0

Views: 1177

Answers (2)

SteAp
SteAp

Reputation: 11999

First $mang isn't initialized, but likely should be:

  // Always initialize variables - good style
  $mang = array();

Instead of passing this ugly $count variable, just append newly discovered data:

  // Will append the right side value as a new last element to $mang
  $mang[] = $arr["user_id"];

Next, you need to pass the variable $anloc:

  $mang1=tree_view ( true, $conn, $anloc );

This version might work better:

function tree_view($conn, $index, $mang ) {

    $q=mysql_query(  'SELECT user_id '
                   . '  FROM thanhvien '
                   . ' WHERE gioithieu = "' . mysql_real_escape_string ( $index ) . '"', 
                   $conn 
                  );

    while( $arr = mysql_fetch_assoc( $q ) ) {

        // better compare type-safe
        if ( true === truongban( $conn, $arr["user_id"], 1 ) ){

            // append found element
            $mang[ ] = $arr["user_id"];

        }

        tree_view( $conn, $arr["user_id"], $mang ); 

    } 

    return $mang;

} // tree_view

Upvotes: 0

Well, the problem I see is that you are not doing anything with the array returned from the recursive call, here in this line:

tree_view(false,$conn,$arr["user_id"]);

I would recommend including both the array and the count on the method parameters (using a static variable is not recommended). So it would be like this:

function tree_view($conn, $index, $mang, &$count)
{
    $q=mysql_query("SELECT user_id FROM thanhvien WHERE gioithieu='".$index."'",$conn);

    while($arr=mysql_fetch_assoc($q)) 
    { 
        if (truongban($conn,$arr["user_id"],1)==true){
            $mang[$count]=$arr["user_id"];
            $count++;
        }
        tree_view($conn,$arr["user_id"], $mang, $count); 
    } 
    return $mang;
} 

And you would invoke your method like this:

$mang1[0] = "";
$count = 0;
$mang1 = tree_view ($conn, anloc, $mang1, $count); print_r($mang1);

Upvotes: 1

Related Questions