How to access values from select() in yii2?

by scotty_walker , in category: PHP General , 8 months ago

How to access values from select() in yii2?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by hal.littel , 8 months ago

@scotty_walker 

In Yii2, the select() query in ActiveRecord returns an array of rows from the database table. To access the values from select(), you can use the following steps:

  1. Execute the select() query and store the result in a variable:
1
$data = YourModel::find()->select('column1, column2')->all();


  1. Iterate through the result and access the values:
1
2
3
4
5
6
foreach ($data as $row) {
    $value1 = $row['column1'];
    $value2 = $row['column2'];
    // Access more columns if needed
    // ...
}


Note that in the select() method, you need to pass the names of the columns separated by commas. In the foreach loop, you can access the values using the array index with the column name.