Class Account extends CI_Model {
private $tbl_rest = array();
private $tbl_fields = array('bs_id', 'bs_name', 'bs_type', 'bs_sub');
function get_data($dataid){
$this->db->select( '*' );
$this->db->from( $this->tbl_name );
$this->db->where( $this->tbl_key, $id );
$query = $this->db->get();
if( $query->num_rows() > 0 )
{
foreach ($query->result() as $row)
{
$this->tbl_rest[] .= '<li id="'.$row->bs_id.'">'.$row->bs_name.'</li>';
}
echo( json_encode( array( 'tdata' => $this->tbl_rest ) ) );
} else {
echo( false );
}
}
}
When I change $query->result() like this
'<li id="'.$row->$this->tbl_fields[0].'">'.$row->$this->tbl_fields[1].'</li>';
I starting getting error “Object of class could not be converted to string”
My Question is:
-
Is possible to convert an array string to object?
-
And how to make $row->$this->tbl_fields[0] happen, so I do not always have to write the name of the field.
This is a basic order of operations issue. PHP doesn’t know if you want some dynamic
$thisproperty of the row, or the$this->tbl_fields[0]property of the row.Try this:
Additionally, I would recommend defining the model’s
$tbl_fieldsproperty as either static or constant, as it doesn’t change at run-time or for specific instances of the class:Furthermore, hard-coding array references to specific column names is somewhat counter-productive, unless you know that [0] will always be the ID, and [1] will always be the name (in which case, you might as well set a static prefix for the column names and use that instead of the
$tbl_fieldsarray).Better yet, because all you’re doing here is a key/value pair (I assume you want to re-use this pattern for other API methods…), you could simply select the fields the way you want to use them. Here’s what I would recommend: