2014-02-22 44 views
-2

我有我的代碼在這裏用以下方法:掌握foreach循環從對象stdClass的多個項目

$db = DB::getInstance(); 
$templates = $db->get('templates', array('user_id', '=', 'username')); 
$templates = $templates->results(); 

echo '<pre>', print_r($templates), '</pre>'; 

它返回這樣的:

Array 
(
    [0] => stdClass Object 
     (
      [user_id] => username 
      [template_id] => 2 
      [template_name] => invoice1 
      [template_description] => dear {{customer}}, 

      The {{item}} will cost {{price}}. 
     ) 

    [1] => stdClass Object 
     (
      [user_id] => username 
      [template_id] => 3 
      [template_name] => invoice2 
      [template_description] => Dear {{customer}}, 

      You have selected {{package type}} service. Your {{item}} will cost {{price}}. 
     ) 

我可以成功地從一開始一個 template_description這樣的foreach循環陣列:

foreach($templates[1] as $key=>$value){   
     $value;   
    } 

但是,我有多個 template_descriptions我想得到,我不知道如何。我不熟悉foreach循環和對象。

如果我刪除從「$模板」的號碼,我得到的錯誤:

Fatal error: Cannot use object of type stdClass as array in C:\xampp\htdocs\email\test.php on line 15 
+1

'的foreach($模板as $ tpl)echo $ tpl ['template_description'];' –

+0

爲什麼迭代只有一個結果項目在冷杉T' YOu應該在循環中省略'[1]'('$ templates [1]')。 – feeela

+0

沒有[1]我得到錯誤'致命的錯誤:不能使用stdClass類型的對象作爲數組在第15行C:\ xampp \ htdocs \ email \ test.php' – SkillSet12345

回答

2

爲什麼你只有一個元素(第二對象)的循環呢?從foreach

foreach($templates[1] as $key=>$value){ 
       ^Wrong way 

刪除[1]這樣做:

foreach($templates as $obj){   
     echo $obj->template_descrption; 
    } 
+0

因爲沒有它我得到'致命錯誤:不能使用類型爲stdClass的對象作爲第15行的C:\ xampp \ htdocs \ email \ test.php中的數組' – SkillSet12345

+1

是將您的循環更改爲我提供的循環並再試一次 –

+0

它的工作原理,謝謝 – SkillSet12345

1

您只需從你的foreach省略數組鍵,就像這樣:

foreach($templates as $template){   
    echo $template->template_description;   
} 
1
foreach($templates as $template){ 
     foreach($template as $key=>$value){ 
        echo $value; 
     } 
}