简体   繁体   中英

Yii2 Query : access array elements in object returned by a query

I'm writing this query in yii2 -

$senderInfo[] = Customers::find()->where(['cust_id' => $resShipment['ship_shipper_id'], 'cust_country_code' => Yii::$app->user->identity->country_code])->distinct()->all();

and getting this as a result -

Array ( [0] => Array ( ) ) Array ( [0] => Array ( ) [1] => Array ( ) ) Array ( [0] => Array ( ) [1] => Array ( ) [2] => Array ( [0] => common\models\Customers Object ( [_attributes:yii\db\BaseActiveRecord:private] => Array ( [cust_id] => 79 [cust_user_id] => 2 [cust_designation] => Mr [cust_fname] => abcd [cust_mname] => xyz [cust_lname] => xyz [cust_country_code] => 91 [cust_mobile] => 8888888888 [cust_email] => abcdxyz@gmail.com [cust_id_proof] => [cust_country] => [cust_state] => [cust_city] => [cust_location] => [cust_street] => [cust_address] => delhi [cust_pobox] => 02881 [cust_additional_detail] => [cust_picture] => [verified] => Yes [created] => 2016-04-20 14:45:42 [updated] => 0000-00-00 00:00:00 [deleted] => No ) [_oldAttributes:yii\db\BaseActiveRecord:private] => Array ( [cust_id] => 79 [cust_user_id] => 2 [cust_designation] => Mr [cust_fname] => abcd [cust_mname] => xyz [cust_lname] => xyz [cust_country_code] => 91 [cust_mobile] => 8888888888 [cust_email] => abcdxyz@gmail.com [cust_id_proof] => [cust_country] => [cust_state] => [cust_city] => [cust_location] => [cust_street] => [cust_address] => delhi [cust_pobox] => 413714 [cust_additional_detail] => [cust_picture] => [verified] => Yes [created] => 2016-04-20 14:45:42 [updated] => 0000-00-00 00:00:00 [deleted] => No ) [_related:yii\db\BaseActiveRecord:private] => Array ( ) [_errors:yii\base\Model:private] => [_validators:yii\base\Model:private] => [_scenario:yii\base\Model:private] => default [_events:yii\base\Component:private] => Array ( ) [_behaviors:yii\base\Component:private] => Array ( ) ) ) )

But, because of the empty arrays in the start of this array, I can't access the elements. I've to populate it in a for(strictly) loop, after it gets accessible.

If you want the result in array you can use ActiveRecord function toArray()

 $myModel = Customers::find()->
    where(['cust_id' => $resShipment['ship_shipper_id'],
    'cust_country_code' => Yii::$app->user->identity->country_code])->distinct()->all();

$senderInfo = myModel->toArray();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM