2010-11-02 76 views
2

我遇到了在Codeigniter中的結果中添加「子結果」的問題。不知道如何添加到這個對象。


$result->{$record_id}->threads = $threads; 

應該等於像這樣

$result->1->threads = $threads; 

,但我無法得到它的工作...我不是新的OOP,但是這是第一次我試着去做這個。

<?php 

function get() { 

$this->db->select(array(

    'record_id', 'record_data', 'record_date', 

)); 

$this->db->from('records'); 

$sql = $this->db->get(); 
$records = $sql->result(); 

foreach($records as $record){ 

    $record_id = $record->record_id; 

    $this->db->select(array(

    'thread_id', 'thread_parent', 'thread_data', 'thread_date', 

)); 

    $this->db->from('records_thread'); 
    $this->db->where(array(

    'thread_recordid' => $record_id, 

)); 

    $sql = $this->db->get(); 
    $threads = $sql->result(); 

    # this is where i'm having issues \/ 

    $records->{$record_id}->threads = $threads; 

} 

return $records; 

} 
?> 

我不想使用數組,並且在視圖文件上使用這些數據更容易。

回答

3

我想你只需要:

$record->threads = $threads; 

編輯:

你只需要在你的foreach分配基準(注意&旁邊$record):

foreach($records as &$record) 
{ 
    //... 
    $record->threads = $threads; 
} 

return $records; 
+0

我很想知道這是否有效。如果我不得不猜測,我會想象它不會,僅僅因爲我假設PHP不會在每個foreach循環中創建一個指向原始對象的指針。雖然我可能是錯的。 – treeface 2010-11-02 23:07:36

+0

是的,這不會附加到每個記錄的ID。它只是簡單地創建一個單獨的對象元素。 – hatfieldajoshua 2010-11-02 23:32:51

+0

@jhat - 將單獨的對象元素附加到具有該ID的$記錄中的記錄。它實際上通過ID附加到每條記錄。雖然你確實需要對你的foreach進行一些細微的調整。查看更新後的答案。 – rojoca 2010-11-03 00:13:09

0

如果rojoca顯示的方法不起作用,您可以這樣做:

$records = $sql->result_array(); 

然後通過循環像往常一樣(除了做$record_id = $record['record_id']代替$record->record_id),並引用您的行這樣的:

$records[$record_id]['threads'] = $threads; 

雖然你可能不希望如此嚴重依賴於RECORD_ID列總是與完美匹配您的迭代索引。