M
M
Max DangerPro2016-11-22 01:06:08
Yii
Max DangerPro, 2016-11-22 01:06:08

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();

I need each received entry from the NAME field to be trimmed by the first letter, I have a function for this:
function getFirstLetter($str) {
      return mb_substr($str, 0, 1, 'utf-8');
}

All of the above is done in:
public function actionAbc() {
      //здесь код
}

And I have a problem how to do all this correctly, including running the array through a loop so that I can pass data to getFirstLetter(). Thank you very much in advance))

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Maxim Timofeev, 2016-11-22
@DangerPro

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');
}

further where necessary:
foreach(Book::find()->select('id,name')->all() as $one){
echo $one->firstLetter;
}

T
Tema, 2016-11-22
@Tem_ka

public function actionAbc() {
    $nameBook = Book::find()->select('id,name')->asArray()->all();
    foreach ($nameBook as &$book) {
        $book['name'] = getFirstLetter($book['name']);
    }
    return $nameBook;
}

A
Abdula Magomedov, 2016-11-22
@Avarskiy

$nameBook = Book::find()->select(['id', 'name' => 'LEFT(name, 1)'])->asArray()->all();

or
$nameBook = ArrayHelper::getColumn($nameBook, function($row){
    getFirstLetter($row['name']);
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question