A
A
Alexander Ivanov2017-03-28 09:07:29
Yii
Alexander Ivanov, 2017-03-28 09:07:29

Why doesn't foreach work in yii2?

Everything is displayed through the wardump, so $news1[0]["title"] is also displayed, but not through foreach.

<?php
echo "<pre>";
echo var_dump($news1);
echo "</pre>";
//?>
<?//=$news1[0]["title"]?>
<?//=$news1[1]["title"]?>
<?//=$news1[2]["title"]?>
<?foreach ($news1 as $val){?>
  <?=$val?>
<?}?>

controller
public function actionNews1()
  {
    $news1 = News1::find()->all();
    return $this->render('news1',[
      'news1' => $news1
    ]);
  }

model
namespace app\models;
use Yii;
use yii\db\ActiveRecord;
class News1 extends ActiveRecord{
}

var_dump
array(3) {
  [0]=>
  object(app\models\News1)#67 (8) {
    ["_attributes":"yii\db\BaseActiveRecord":private]=>
    array(3) {
      ["id"]=>
      int(1)
      ["title"]=>
      string(18) "Страница 1"
      ["content"]=>
      string(23) " содержимое 1"
    }
    ["_oldAttributes":"yii\db\BaseActiveRecord":private]=>
    array(3) {
      ["id"]=>
      int(1)
      ["title"]=>
      string(18) "Страница 1"
      ["content"]=>
      string(23) " содержимое 1"
    }
    ["_related":"yii\db\BaseActiveRecord":private]=>
    array(0) {
    }
    ["_errors":"yii\base\Model":private]=>
    NULL
    ["_validators":"yii\base\Model":private]=>
    NULL
    ["_scenario":"yii\base\Model":private]=>
    string(7) "default"
    ["_events":"yii\base\Component":private]=>
    array(0) {
    }
    ["_behaviors":"yii\base\Component":private]=>
    array(0) {
    }
    ...
 }
}

It also doesn't throw any errors.
Maybe the problem is in SQL or that there is no public access?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mikhail Konyukhov, 2017-03-28
@cimonlebedev

<?php foreach ($news1 as $val){?>
  <?= var_dump($val); ?>
<? } ?>

What will var_dump($val) show? An object. If you want to display the title, then it is done like this:
<?php foreach ($news1 as $val){?>
  <?= $val->title; ?>
<? } ?>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question