how to get single value from array in codeigniter

2019-02-28 05:40发布

问题:

I stored some data to an array using this code

$this->data['result']    =   $this->mymodel->search($keyword);

when I print my result by using print_r($this->data);

it shows like this

Array ( [base_url] => http://localhost/pelikanartline.com/ [result] => Array ( [0] => stdClass Object ( [product_id] => 2 [product_code] => 167007 [product_name] => ARTLINE VIVIX HIGHLIGHTERS 10PK YELLOW [product_discription] => some description [xylene_free] => y [rohs_compliant] => y [product_features] => some text ) ) )

now I want to store product_id value to a variable like pro_id. please help me to do this.

回答1:

Try this:

 $pro_id = [];

 foreach($this->data['result'] as $key => $val){
    $pro_id[] = $val->product_id;
 }

 print_r($pro_id);


回答2:

If your model returns only one record, you can use this shortcut:

$pro_id = $this->data['result'][0]->product_id;