I need to convert a php object array into a javascript variable inorder for it to be used in 'easyautocomplete' plugin. Here is a rundown of what I'm trying to achieve:
var_dump of PHP object returned from database:
array(223) {
[0]=>
object(stdClass)#5 (9) {
["id"]=>
string(2) "10"
["no"]=>
string(3) "CN1"
["name"]=>
string(10) "Cyclops"
}
[1]=>
object(stdClass)#6 (9) {
["id"]=>
string(2) "11"
["no"]=>
string(3) "CN2"
["name"]=>
string(11) "Professor X"
}
..
..
Required javascript format:
var characters = {
data: [
{"name": "Cyclops", "id": 1},
{"name": "Professor X", "id": 2}
],
getValue: "name",
list: {
onSelectItemEvent: function() {
var value = $("#character1").getSelectedItemData().id;
$("#character").val(value).trigger("change");
}
}
};
What I tried:
var characters = <?php echo json_encode(['data' => $chars]); ?>;
Result:
var characters = {
"data": [
{"id":"10","no":"CN1","name":"Cyclops"},
{"id":"11","no":"CN2","name":"Professor X"}
]};
It seems I have almost got the result I need, but I don't know how I'll append the remaining properties starting from getValue : "name" list: { .....
to the character variable.
Also, it seems the resulting variable has double quotes around the "data" attribute but I'm not sure if that'd cause a problem.
Link to the example I'm trying to implement: Link