我的代码在这里使用以下方法:
$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}}.
)
我可以使用这样的foreach循环从数组中成功获得一个 template_description:
foreach($templates[1] as $key=>$value){
$value;
}
但是,我想要获得多个 template_descriptions,我不知道如何。我对foreach循环和对象不是很熟悉。
如果我从'$ templates'中删除号码,我会收到错误:
Fatal error: Cannot use object of type stdClass as array in C:\xampp\htdocs\email\test.php on line 15
答案 0 :(得分:2)
为什么只循环一个元素(第二个对象)?从[1]
foreach
foreach($templates[1] as $key=>$value){
^ Wrong way
这样做:
foreach($templates as $obj){
echo $obj->template_descrption;
}
答案 1 :(得分:1)
您只需要省略foreach中的数组键,如下所示:
foreach($templates as $template){
echo $template->template_description;
}
答案 2 :(得分:1)
foreach($templates as $template){
foreach($template as $key=>$value){
echo $value;
}
}