Skip to main content
Code Review

Return to Question

edited tags
Link
Mast
  • 13.8k
  • 12
  • 57
  • 127
Bumped by Community user
Source Link
Tolani
  • 2.5k
  • 7
  • 31
  • 49

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

  1. Use a class definition instead that manages the above?
  2. Use the \stdClass object to dynamically create this structure?
  3. Is there a neater way to do this as the dynamic properties will grow depending on the request from the chatbot
  4. Am I overthinking?
lang-php

AltStyle γ«γ‚ˆγ£γ¦ε€‰ζ›γ•γ‚ŒγŸγƒšγƒΌγ‚Έ (->γ‚ͺγƒͺγ‚ΈγƒŠγƒ«) /