phploopsobject

How to loop through properties in a flat object


There is a table contains columns like

username,settings1,settings2,settings3

username is a unique and settings1,2,3 is contain 0 or 1 values.

$query = $this->db->query("SELECT * FROM tbl_users WHERE username = 'test'");
$queryrow = $query->row();

so I want to select the row that matching to username and loop through columns and check which column contain 0's and 1's.

I can do this by writing a if statement for every column though, like

if($queryrow->settings1=="1"){
..
}

there is like 7 columns in table so instead of writing 7 if statements, any other way to do this? I'm using CodeIgniter 2.0.2


Solution

  • You can iterate objects

    // use active record to work less and be safer
    $this->db->where('username', 'test');
    $query = $this->db->get('tbl_users');
    
    foreach ($query->result() as $row)
    {
        // iterate the row object
        foreach($row as $key => $item)
        {
            if($row->$key == "1")
            {
                // your code
            }
        }
    }
    

    If all you need to do in this loop is checking those values, you should do a SELECT to have only those items in $row, and avoid having "username"

    $this->db->select('setting1, setting2, setting3');
    

    Otherwise, if you want to keep username, the IF statement could be rather

    if(in_array($key, array('setting1', 'setting2', 'setting3')) && $row->$key == "1")