Answer the question
In order to leave comments, you need to log in
What is the correct way to run an array through a foreach() loop?
Hello. Please help me with the code, otherwise I'm not good at this.
I made a selection from the database and got an array.
$nameBook = Book::find()->select('id,name')->asArray()->all();
function getFirstLetter($str) {
return mb_substr($str, 0, 1, 'utf-8');
}
public function actionAbc() {
//здесь код
}
Answer the question
In order to leave comments, you need to log in
asArray()
- remove, because you will get an array, while you need a model object, in order for your getFirstLetter method to work, it must be placed in the model and made public, something like this:
public function getFirstLetter() {
return mb_substr($this->name, 0, 1, 'utf-8');
}
foreach(Book::find()->select('id,name')->all() as $one){
echo $one->firstLetter;
}
public function actionAbc() {
$nameBook = Book::find()->select('id,name')->asArray()->all();
foreach ($nameBook as &$book) {
$book['name'] = getFirstLetter($book['name']);
}
return $nameBook;
}
$nameBook = Book::find()->select(['id', 'name' => 'LEFT(name, 1)'])->asArray()->all();
$nameBook = ArrayHelper::getColumn($nameBook, function($row){
getFirstLetter($row['name']);
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question