2015-12-28 223 views
0

我正在開發一個web服務和android應用程序web服務是在PHP從MySQL數據庫獲取數據...我遇到的問題是,一些項目有多個細節,但我的代碼是隻爲每個項目提供一個細節。我以JSON格式獲取數據。嵌套的while循環不工作

您可以檢查此Here

這裏是我的代碼提前

function requiredData(){ 

    $db = $this->dbConnection(); 
    //$sql = "SELECT * FROM projects JOIN project_details ON projects.project_id=project_details.project_id"; 
    $sql = "SELECT * FROM projects"; 

    $queryResult = $db->query($sql); 

     if($queryResult->num_rows > 0){ 

      while($row = $queryResult->fetch_assoc()){ 

       $pid = $row['project_id']; 
       $detailsql = "SELECT * FROM project_details WHERE project_id=$pid"; 
       $sqlResult = $db->query($detailsql); 
       if($sqlResult->num_rows > 0){ 
        while ($d = $sqlResult->fetch_assoc()){ 
         $r = array(
          "project_id" => $d['project_id'], 
          "project_detail" => array(
           "work_done" => $d['project_detail'], 
           "payment_for_work" => $d['project_payment'], 
           "payment_status" => $d['project_payment_status'], 
           "detail_id" => $d['project_detail_id'] 
          ) 
         ); 
        } 
       } 
       $results[$row['project_name']] = array(
        "project_id" => $row["project_id"], 
        "project_start_date" => $row["project_start_date"], 
        "project_due_date" => $row["project_due_date"], 
        "project_currency" => $row["project_currency"], 
        "project_work_details" => $r 
       ); 


      } 
     } 
     return $results; 
} 

感謝您的幫助

+0

什麼?我檢查了你指定的鏈接,它顯示了多個項目。你到底想要什麼? – Umair

+0

一些項目有多個project_details ...但目前有一個顯示...例如項目ID 20有多個project_detail數組,,,但只有一個顯示出來... – FaISalBLiNK

回答

0

的問題是在第二while循環。您正將數組分配到$r,並且每次都覆蓋$r值。因此,我現在將數組賦值給另一個數組,所以它會變成2維數組,如下所示:

   while ($d = $sqlResult->fetch_assoc()){ 
        $r[] = array(
         "project_id" => $d['project_id'], 
         "project_detail" => array(
          "work_done" => $d['project_detail'], 
          "payment_for_work" => $d['project_payment'], 
          "payment_status" => $d['project_payment_status'], 
          "detail_id" => $d['project_detail_id'] 
         ) 
        ); 
       } 

現在你可以使用$r,它會有多個項目細節。

+0

我已經測試過,當我使用$ r []我得到一個無限循環...我編輯了代碼,並用$ r []替換$ r爲你的這個... http://projects.base29.com/webservice/?q=projects – FaISalBLiNK

+0

使用'$ r []',沒有任何東西可以無限循環,看起來你的數據庫中有太多的記錄。你有沒有嘗試通過限制選擇項目查詢? – JazyK

+0

嗯..沒有嘗試限制記錄...沒有來到我的腦海中..會嘗試讓你知道... – FaISalBLiNK