1

I'm just trying to get states based on the selection of the country. While I'm trying to getting states I'm getting the following error.

<p>Severity: Notice</p>
<p>Message:  Trying to get property of non-object</p>
<p>Filename: General/Common.php</p>
<p>Line Number: 19</p>

Here is my Model

function get_states($param_countryid)
    {
        $get_states = $this->db->order_by($this->state_name, 'asc')->where($this->c_id ,$param_countryid)->get($this->tbl_state)->result_array();
        $states = array();
        foreach ($get_states as $state_row) {
            $states[$state_row[$this->state_id]] = $state_row[$this->state_name ];
        }
        return $states;
    }

This is my controller(Common.php)

$data['states'] = $this->commodel->get_states($this->input->post('country_id'));
        $states = null;
       foreach ( $data['states']  as $states_row ) {
            $states .= "<option value='" . $states_row->id. "'>" . $states_row->name. "</option>"; Line Number 19 mentioned in the error.

        }
        echo $states;

What is I'm getting from print_r($data['states']) is (Assume a country is selected,for example, India)

Array ( [1] => Andaman and Nicobar Islands [2] => Andhra Pradesh [3] => Arunachal Pradesh [4] => Assam [5] => Bihar [6] => Chandigarh [7] => Chhattisgarh [8] => Dadra and Nagar Haveli [9] => Daman and Diu [10] => Delhi [11] => Goa [12] => Gujarat [13] => Haryana [14] => Himachal Pradesh [15] => Jammu and Kashmir [16] => Jharkhand [17] => Karnataka [19] => Kerala [20] => Lakshadweep [21] => Madhya Pradesh [22] => Maharashtra [23] => Manipur [24] => Meghalaya [25] => Mizoram [26] => Nagaland [29] => Odisha [31] => Pondicherry [32] => Punjab [33] => Rajasthan [34] => Sikkim [35] => Tamil Nadu [36] => Telangana [37] => Tripura [38] => Uttar Pradesh [39] => Uttarakhand [41] => West Bengal )

When I tried

$states .= "<option value='" . $states_row['id']. "'>" . $states_row['name']. "</option>";

Im getting the following error.

Message: Illegal string offset 'id'

Message: Illegal string offset 'name'

Please advice me where I'm doing my mistake in this code.

Community
  • 1
  • 1
Sudhi Sr
  • 139
  • 1
  • 2
  • 10
  • Give this a read: https://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php?rq=1 more specific is [this](https://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php/26572398#26572398) – hungrykoala Jun 08 '18 at 07:06

1 Answers1

1

As you can see from your print_r($data['states']) you are getting a key which is the id of the state and the value of each element is the name. So you need to do the output like...

foreach ( $data['states']  as $id=>$name ) 
{
  $states .= "<option value='" . $id. "'>" . $name. "</option>"; 
}
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55