How can I create an associative array from a database object and json_encode as an object instead of an array?
I am new to PHP and developing an application using Yii. I have a database object where all I got are all table records. I wanted to create an associative array from this object and then encode that array in json_encode. However, my desired result, which is objects instead of an 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"}]}
+3
source to share