2010-04-05 44 views
1

我嘗試使用CodeIgniter編寫站點,但我遇到了PHP問題。我相信這很簡單,不會錯。但我不知道從,只是一個笨的新手:)PHP - CodeIgniter - 爲foreach提供的參數無效()

<html> 
    <head> 
     <title><?=$page_title?></title> 
    </head> 
    <body> 
     <?php foreach($result as $row):?> 
     <h3><? echo $row->title; ?></h3> 
     <p><? echo $row->text; ?></p> 
     <?php endforeach;?> 
    </body> 
</html> 

我有一個錯誤,從這個文件中的錯誤:

遇到

一個PHP錯誤

嚴重性:警告

消息:視圖/ hellowor:用於 的foreach()

文件名提供參數無效ld_view.php

行號:6

在此先感謝您閱讀本:)

回答

2

您提供給foreach循環的變量是一個數組。如果提供的變量的值不是下面的解決方案的數組,則可以跳過該foreach。

<?php if(is_array($result)): ?> 
<?php foreach($result as $row):?> 
<h3><? echo $row->title; ?></h3> 
<p><? echo $row->text; ?></p> 
<?php endforeach;?> 
<?php endif; ?> 
+2

這將停止錯誤,但它不會幫助他確定發生了什麼。 Alex Lawford在這裏做出了最好的猜測,要麼他試圖使用數據庫對象,要麼他的模型在某處有FALSE。 – 2010-04-07 09:05:47

2

$結果是不數組。

嘗試在foreach之前用is_array檢查。

和調試爲什麼$結果不是數組:P

5

嘗試foreach($result->result() as $row) - 它可能是你試圖迭代Codeigniter的活動記錄返回的對象。

3

如果你想知道變量中有什麼可以輸出它!

var_dump($result); 

這會立即告訴你發生了什麼事。我的猜測是,你已經從你的模型中返回了FALSE,或者你正在使用DB對象,而不是result()或result_array()(正如Alex所建議的那樣)。

2

你可以使用empty php函數並做類似

<? 
    if(!empty($results)){ 
     echo " 
     foreach($result as $row){ 
     <h3>".$row->title."</h3> 
     <p>".$row->text".</p> 
      "; 
     } 
    }else{ 
     echo "<p>no results<p/>"; 
    } 
?> 
0

首先,您需要確保傳遞給您的視圖的數據數組的確被稱爲$data['result']

在控制頁面,它應該是這個樣子:

// you need to put some data here for checking the number of results returned 

if($numberOfRows > 0){ 
$data['result'] = $this->Yourmodel->methodName($arguments); 

$this->load->view('yourView'); 
} 

else{ 
$this->load->view('yourCustomMissingOrErrorView'); 
} 

在視圖頁面應該是

<?php 

// note if you are just intitialiizing variables, remove the echo statements and put it  before all of your html. if you are looping for output then put it where it needs to go in the html 

foreach($result as $value){ 
$title = $this->value->title; // just makes it easier to use if you need to use elsewhere 
$text = $this->value->text; // just makes it easier to use if you need to use elsewhere 

echo "<h3>" . $title . "</h3>"; 
echo "<p>" . $text . "</p>"; 
} 
?> 
0

你需要在控制器

定義$數據[「結果」]
//Controller File 
function yourControllerMethod() 
{ 
    $this->main(); 
    $this->load->model('yourModel'); 
    $data['result'] = $this->yourModel->getResultMethod(); 
    $this->load->view('yourView',$data); 
} 

//Model File 
function getResultMethod() 
{ 
    $this->db->from($this->yourTable); 
    $query = $this->db->get(); 
    $rows = $query->result(); 
    return $rows; 
} 
0

老兄,這個錯誤「爲foreach()提供的無效參數」大多發生。當您將關聯數組傳遞給foreach時,它爲null。用echo語句仔細檢查你的關聯數組。不要傳遞null關聯數組來foreach循環。