2011-10-31 139 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

這可以使您能夠直接從數據庫中查詢所需的值。如果你有你的桌子的結構,我很樂意幫忙。