2011-10-31 140 views
0

我有一个数据库满了需要更新旧零件号码价格的自动启动号码。每行都有一个零件号(字段名称“master”),一个价格和一个带有被取代(较新)零件号(字段名称“pnc”)的字段。脚本需要检查“pnc”字段是否为空。如果不是,它应该去拿这个数字的价格。很简单。递归函数没有任何返回

但是,某些零件号码在达到最新的零件号和价格之前会有数量未知的数字。所以,我认为递归函数是最好的解决方案。但是,它不能正常工作。下面的代码:

public function updatePricing() 
    { 
     //method to update pricing by referencing supersession prices 
     $sql = "SELECT * FROM prices"; 
     $result = mysql_query($sql); 
     $num_rows = mysql_num_rows($result); 

     for($i=0;$i<2000;$i++) //using 2000 for testing, use $num_rows after 
      { 
       $row = mysql_fetch_array($result); 
       $id = $row['id']; 
       $super_num = $row['pnc']; 

       //if there is a supersession in this row find original 
       if(!empty($super_num)) 
        { 
         $final_super_price = $this->findSuperPrice($super_num); 

         echo "partnum: " . $row['master']; 
         echo "&nbsp;&nbsp;"; 
         echo "price: " . $final_super_price . "<br /><br />"; 
        } 
      } 
    } 

public function findSuperPrice($part_num) 
    { 
     $sql = "SELECT * FROM prices WHERE master='" . $part_num . "'"; 
     $result = mysql_query($sql); 
     $row = mysql_fetch_array($result); 

     if (empty($row['pnc'])) //if there aren't any supersession numbers 
      { 
       $final_price = $row['list']; 
       return $final_price; 
      } 
     else //recursively call itself until we find the last number 
      { 
       $this->findSuperPrice($row['pnc']); 
      } 
    } 

发生了什么事是updatePricing()函数运行,直到它找到已在“PNC”字段中输入一行。当它发生时,调用findSuperPrice()函数。 findSuperPrice()函数应该递归运行,直到“pnc”字段为空。发生这种情况时,会返回一个数字。然而,如果它实际上到达findSuperPrice()中的if语句的else部分,它不会返回任何东西。基本上,如果它超过一个深度。我没有收到任何错误,只是返回一个空白语句。我已经验证了那里有信息,它也应该返回。谢谢。

另外,我应该提到这是一个更大的类内。其他人对这两种方法没有影响。

+1

请考虑使用'do {} while()'循环代替。虽然你的数据库结构是递归的,但不需要使用实际的递归调用来在树上工作。 –

回答

4

您需要返回一个值。更改此代码:

else //recursively call itself until we find the last number 
    { 
     $this->findSuperPrice($row['pnc']); 
    } 

要这样:

else //recursively call itself until we find the last number 
    { 
     return $this->findSuperPrice($row['pnc']); 
    } 
2

您目前没有得到返回值,因为如果$row['pnc']不为空,findSuperPrice的结果将被忽略。正确地返回递归调用的值:

return $this->findSuperPrice($row['pnc']); 
1

你缺少的else盒内findSuperPrice return语句。

但是...它看起来像是抽取了大量数据来查看/操作只有一个字段。您也可以在mysql中编写函数,类似于我在此处发布的函数:MySQL: Get Root Node of Parent-Child Structure

这可以使您能够直接从数据库中查询所需的值。如果你有你的桌子的结构,我很乐意帮忙。