Get data from model and convert in json

Hello,

in my controller:


    public function actionIndex()

    {

		$data = Marker::find()->all();

		return $this->render('index', array('data' => $data ));

    }

Then, in index view the data are shown (so I’m sure that till here it’s working)


<p><?php foreach ($data as $post): ?></p>

<p><?php echo "ID: " . $post->id; ?></p>

<p><?php echo "Descr: " . $post->description; ?></p>

<p><?php echo "Addr.: " . $post->address; ?></p>

<p><?php echo "Lat: " . $post->lat; ?></p>

<p><?php echo "Long: " . $post->lng; ?></p>

<?php endforeach; ?>

Now my problem is to convert the array in json format. I try this, always in an script view:


  var data = <?php echo json_encode($data); ?>;

  

  for (var i = 0; i < data.length; i++) {

  	displayLocation(data[i]);

  }

but, don’t work. :frowning:

After further investigation discoverd that this action


    public function actionIndex()

    {

                $data = Marker::find()->all();

                return $this->render('index', array('data' => $data ));

    }

return the data in this format:


Array ( [0] => app\models\Marker Object ( [_attributes:yii\db\BaseActiveRecord:private] => Array ( [id] => 9 [photo] => foto [description] => Incidente 2 [lat] => 45.619778 [lng] => 13.815197 [city] => 0 [address] => via antonio grego 25 trieste [numero] => [userid] => 1 [created] => 2014-10-17 23:48:44 [modified] => 2014-10-19 19:44:21 [status_id] => 1 ) [_oldAttributes:yii\db\BaseActiveRecord:private] => Array ( [id] => 9 [photo] => foto [description] => Incidente 2 [lat] => 45.619778 [lng] => 13.815197 [city] => 0 [address] => via antonio grego 25 trieste [numero] => [userid] => 1 [created] => 2014-10-17 23:48:44 [modified] => 2014-10-19 19:44:21 [status_id] => 1 ) [_related:yii\db\BaseActiveRecord:private] => Array ( ) [_errors:yii\base\Model:private] => [_validators:yii\base\Model:private] => [_scenario:yii\base\Model:private] => default - etc. -

Instead I would need this type of data:


[{"id":"9","0":"9","photo":"foto","1":"foto","description":"Incidente 2","2":"Incidente 2","lat":"45.619778","3":"45.619778","lng":"13.815197","4":"13.815197","city":"0","5":"0","address":"via antonio grego 25 trieste","6":"via antonio grego 25 trieste","numero":"","7":"","userid":"1","8":"1","created":"2014-10-17 23:48:44","9":"2014-10-17 23:48:44","modified":"2014-10-19 19:44:21","10":"2014-10-19 19:44:21","status_id":"1","11":"1"},{"id":"10","0":"10","photo":"ggg","1":"ggg","description":"Lavori in corso","2": - etc. -

And these data are derived from a direct sql call to the db (and json conversion)


$sth = $db->query("SELECT * FROM marker");

        $locations = $sth->fetchAll();

        echo json_encode( $locations );



It is clear that I don’t know how to right query the database using a controller action to meet up the data in this format. Is there someone can help me, please ?

Edit in your controller:


public function actionIndex()

{

    $data = Marker::find()->asArray()->all(); // edit here

    return $this->render('index', array('data' => $data ));

}

hope it help you! :)

1 Like

Yes, I tried this way too. Your code build array directly, and then it is only need to json encoding and parsing. In other way there is one more passage needed to build array with foreach cicling.

Thank you. At the end my code is coming to work. :slight_smile:

why use views? isn’t better change response format to json and let framework do the rest?

http://www.yiiframework.com/doc-2.0/guide-runtime-responses.html#response-body

I tried this way too, but without success. I try to explain. I saw the guide that you linked and also this one: Tip & Tricks. Trying to work around this point:


$items = ['some', 'array', 'of', 'values' => ['associative', 'array']];

\Yii::$app->response->format = 'json';

return $items;

but it doesn’t send data to the view, only open a page populated with json data. Why I need a view? First because I’m newbee, it is obvious, second because the array it is passed to a javascript in the view (some data needed to build markers in google maps, in this case).

This is the controller action code:


    public function actionIndex()

    {

   		$model = Marker::find()->asArray()->all(); 

    	return $this->render('index', array('model' => $model ));

    }

and this is a snippet of javascript code in the index view:


		var data = '<?= json_encode($model); ?>';

		var datac = JSON.parse(data); //<- maybe this step is redundant


		for (var i = 0; i < datac.length; i++) {

    	        	displayLocation(datac[i]);

      		}



I am absolute sure that will be thousands of others ways to obtain this, but I can’t figure out.

Why I did all this? The program was running fine (first, I did it in an html page), but it was working calling db via php, through a classic file with db, name, password. So I tried to do the same, but using an approach that I think more near to Yii. It is not perfect, I know, maybe it will be possible to move the javascript from the view to right place ( Working with Client Scripts ). But for the moment will be ok so. :slight_smile:

Thanks to all, for your availability

Thank you infinitely