sehummel
sehummel

Reputation: 5568

PHP object oriented foreach loop

I have a CodeIgniter query that brings back an array of objects. My query is querying multiple tables that all have the same field name. So I am using the select to give them aliases. Like this:

SELECT t1.platform_brief b1, t2.platform_brief b2

where t1 and t2 are my two tables. My array when print_r'd returns objects like this:

Array
(
    [0] => stdClass Object
        (
            [b1] => Lorem ipsum
            [b2] => 
        )

    [1] => stdClass Object
        (
            [b1] => 
            [b2] => Sic dolor sit
        )

)

In my foreach, when I echo them, how do I do that? I tried something like this but it didn't work:

<?php foreach ($lasers as $laser) {
echo $laser->?
?>

What do I put in place of the question mark?

EDIT:

Here is my CI query:

$this->db->select('ils1.platform_brief b1, ils2.platform_brief b2');
$this->db->where('ils1.language', $lang);
$this->db->or_where('ils2.language', $lang);
$this->db->join('all_platform_ils975 ils2', 'ils2.laser_id = c.laser_id', 'left');
$this->db->join('all_platform_ils1275 ils1', 'ils1.laser_id = c.laser_id', 'left');
$this->db->join('all_lasers l', 'l.laser_id = c.laser_id', 'inner');
return $this->db->get($lang . '_configure_lasers c')->result();

Upvotes: 0

Views: 3064

Answers (2)

hakre
hakre

Reputation: 197658

You could iterate over each object:

foreach ($lasers as $laser) {
    foreach($laser as $field) {
        if(!empty($field)) echo $field;
    }
}

However, instead you should change the database design / query design to better meet your needs.

Upvotes: 0

user7675
user7675

Reputation:

Judging by your follow-up comment, it sounds like you want to output all the b1 fields for each result, then all the b2 fields. One way:

foreach( array('b1', 'b2') as $fields ) {
    foreach( $lasers as $laser ) {
        echo $laser->$field, '<br>';
    }
}

Upvotes: 2

Related Questions