Friday, 31 August 2018

PHP - how to create an associative array from the database object and json_encode as an object instead of an array?

I am a newbie in PHP and developing an app using Yii. I have a database object where all I got all the records of a table. I wanted to create an associative array from that object and later encode that array in json_encode. However, my desired output,which is objects instead of array, is not coming. can anyone help, plz?

My code:
$info = array();
$category = Category::find()->all();
foreach($category as $key => $value) {
    $info[]=  array(
         "name" =>$value->name,
         "value" =>$value->description
    ) ;
}
echo json_encode($info,JSON_FORCE_OBJECT);

Output:
{"0":{"name":"test","value":"A"},"1":{"name":"test 2","value":"B"}}

Desired Output:
{"category":[{"name":"test","value":"A"},{"name":"test 2","value":"B"}]}


Try to use this:
$info2['category']=$info;
echo json_encode($info2);

0 comments:

Post a Comment