Reputation: 367
How can I get all ActiveRecord objects in Yii2 like an array, which can be iterated by foreach()
.
This is the code which should work but it returns zeros instead of actual data.
public function getAllCategories(){
$categoriesList=[];
$categories= Category::find()->orderBy("id")->all();
foreach ($categories as $category){
$categoriesList[]+=$category->title;
}
return $categoriesList;
}
Upvotes: 1
Views: 5830
Reputation: 177
You have error in Your php syntax - You are using +=, which is not capable to add strings, You should either use just = or .=
Upvotes: 0
Reputation: 2746
If you are getting your objects, you are still able to iterate through them. Try to make following simple change (look at "+=" change to "0"):
public function getAllCategories(){
$categoriesList = array();
$categories = Category::find()->orderBy("id")->all();
foreach ($categories as $category){
$categoriesList[] = $category->title;
}
return $categoriesList;
}
Here is some reference to active record in Yii2: link. With find()->all()
you are getting an array with objects.
Upvotes: 1