Getting multiple items from object stdClass with foreach loop

I have my code here with the following methods:

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

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

Which returns this:

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}}. 
        )

I can successfully get one template_description from the array with a foreach loop like this:

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

However, I have multiple template_descriptions I want to get and I'm not sure how. I'm not very familiar with foreach loops and objects.

IF I remove the number from '$templates' I get the error:

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

Answers


Why are you looping on only one element (the second object)? Remove [1] from foreach

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

Do this:

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

You simply need to omit the array key from your foreach, like so:

foreach($templates as $template){           
    echo $template->template_description;          
} 

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

Need Your Help

Can I leave sockets in SYN_RECV until I'm interested in accepting?

sockets tcp server bittorrent backlog

In a torrent client I've written, I don't accept connections unless I actually want or need more connections. This leads to netstat showing a lot of SYN_RECV, which seems plausible as I haven't yet