2014-06-10 18 views
1

我想在將ResultSet返回給Controller之前更改ResultSet中的行字段。ZF2:更改結果集中的行字段

$resultSet->buffer(); 
foreach ($resultSet as $row) { 
    $row->foo = $newvalue; 
} 
return $resultSet; 

問題是,當我使用緩衝區()函數,我的確可以循環在我的ResultSet,並就我行一些變化,但一旦循環結束所有的變化都沒有了。

我試圖建立在$行的引用:

foreach ($resultSet as &$row) 

但隨後陷入以下異常:

Fatal error: An iterator cannot be used with foreach by reference 

我也試圖爲結果更改爲陣,但出現相同的問題。 我錯過了什麼嗎?

回答

2

我不認爲這是可以通過通常的ResultSet用法。只有在循環中使用array(本例中爲foreach())時,陣列解決方案纔有效。

從任何表類 - 在控制器或視圖文件此數組的

$arr_resultSet = array(); 

foreach ($resultSet as $row) { 
    $row->foo = $newvalue; 

    //Object is assigned instead of converting it to an array. 
    $arr_resultSet[] = $row; 
} 
return $arr_resultSet; 

用法 -

//Here you can access that $row object as if the $resultSet was never converted to array. 
foreach($arr_resultSet as $row) { 
    echo $row->foo;     
} 

不需要的buffer()。我希望它現在可以工作。肯定會尋找一個適當的解決方案。

+0

哇。我試圖使用toArray()函數,但後來它是一團糟,因爲我有嵌套數組而不是對象。你的解決方案非常簡單,我想知道我是如何錯過它的。 它工作正常,似乎是一個合理的解決方案,所以我已經將它設置爲回答。無論如何,如果你想出一個適當的解決方案,我會很高興看到它。 非常感謝:) – Traperac