Best Practice: creating a nested associative array JSON in PHP
It's been a while I have been on here and I hope I still understand the rulesπ. I have recently started learning PHP and WordPress for a Whatsapp Chatbot integration. I have created a webhook on my WordPress site that returns a JSON, which is consumed by Google Dialogflow(Chatbot engine).
For example, my webhook returns something like this
{
"fulfillmentMessages": [
{
"text": {
"text": [
"Text response from webhook"
]
}
}
]
}
To achieve this structure, I have written used this nested associative array
$innerarr= array();
$innerarr[0] = "Text response from webhook";
$newarr = array();
$newarr["fulfillmentMessages"]= array();
$newarr["fulfillmentMessages"][0] = array("text"=>array("text"=>$innerarr));
echo json_encode($newarr);
It works but I'm also thinking, should I
- Use a class definition instead that manages the above?
- Use the \stdClass object to dynamically create this structure?
- Is there a neater way to do this as the dynamic properties will grow depending on the request from the chatbot
- Am I overthinking?