2013-04-06 57 views
0
<?php 
    print_r($optimum); 
    $dataNumRows = count($optimum); 
    ?> 

    <?php for ($i = 0; $i < $dataNumRows; $i++) : ?> 
     <?php echo $cFirstName; ?> 
     <?php echo $cLastName; ?> 
    <?php endfor; ?> 

print_r插在我的視圖顯示以下內容:Codeigniter/PHP如何正確使用for循環?

Array ([cFirstName] => Array ([0] => Tom [1] => Alexa) [cLastName] => Array ([0] => Jones [1] => Planter)) 

我的模型如下

//Get all the customers currently pending 
//install for the user making the request. 
function getAllCustomersPendingInstall() 
{ 
    $data=array(); 

    //Need to use sessions to display proper 
    //records for each user. Temp set id to user #7 
    $id = 7; 

    //query the db and return all record where SalesRepId == $id 
    $query = $this->db->get_where('customers', array('SalesRepId' => $id)); 

     //check logic, if rows exist RETURN all rows, else 
     //return message that no pending installs is available. 
     if($query->num_rows != 0) { 
      foreach($query->result() as $row) { 
       $data['cFirstName'][] = $row->customerFirstName; 
       $data['cLastName'] [] = $row->customerLastName; 
      } 
     } else { 
      $data = "No pending installs available!"; 
      return $data; 
     } 
//the following var_dump is only showing the last record. 
//need to show all rows (which should be 2) 
//var_dump($data); exit; 
return $data;   
} 

我的控制器是以下

{ 
    $this->load->library('table'); 
    $this->load->model('GetData'); 
    $data['optimum'] = $this->GetData->getAllCustomersPendingInstall(); 
    $this->load->view('welcome_message', $data); 
} 

而我的問題是我如何在我的VIEW中正確使用FOR循環,以便我可以遍歷所有返回的行。正如你可以看到print_r正確地返回正確的行 - 但是我無法循環它們。謝謝您的幫助!非常感激!

回答

0

試試這個在您的視圖:

<?php for ($i = 0; $i < $dataNumRows; $i++) : ?> 
    <?php echo $optimum['cFirstName'][$i]; ?> 
    <?php echo $optimum['cLastName'][$i]; ?> 
<?php endfor; ?> 
+0

這不會迴應任何東西 – fyz 2013-04-06 21:51:36

+0

Ups!數組名稱 – Sangar82 2013-04-06 21:53:16

+0

出錯了。謝謝! – fyz 2013-04-06 21:55:54

0

我想你要做的是從數據庫返回的每一行獲得一個關聯數組。糾正我,如果我錯了。

應該解決您的問題

$data = array(); 
$data_index = 0; 
if($query->num_rows != 0) { 
      foreach($query->result() as $row) { 
       $data[$data_index]['cfirst'] = $row->customerFirstName; 
       $data[$data_index]['clast'] = $row->customerLastName; 
       $data_index++; 
      } 
     } else { 
      $data = "No pending installs available!"; 
      return $data; 
     } 
在你看來

然後(其中$customer$data陣列)

<?php foreach($customer as $c):?> 
<?php echo $c['cfirst'];?> 
<?php endforeach;?> 
+0

這個工作,但什麼是data_index,爲什麼有必要讓代碼運行? – fyz 2013-04-06 21:54:12

+0

您需要創建一個數組數組。你之前的做法是用2個鍵創建一個關聯數組,然後覆蓋模型中每個foreach循環迭代中的值。 – Ethan 2013-04-06 21:57:12

+0

謝謝你的幫助,雖然你的答案正常工作我選擇上述答案,因爲我覺得它與我的原始代碼更好地混合。謝謝! – fyz 2013-04-06 22:05:48