-1

Up until now I have just used PHP's json_encode() on simple rows of data, for example

{
  "name":"bob",
  "age":"22"
}

However I have the need to return JSON which has arrays.

Example output is

{
  "success":true,
  "payload":
    {
      "venuedata":
      {
        "id":"1",
        "name":"venue name"
      },
      "menus": [
        {"menuid":"1","menuname":"food","items": [{"item":"pizza","cost":"$12.50"},{"item":"burger","cost":"$14.50"}]},
        {"menuid":"2","menuname":"drinks","items": [{"item":"pint of beer","cost":"$5.50"}]}
      ]
  }
}

Now, the venuedata object will come from one PDO query, and the menus will come from another query and the items for each menu will come from another query.

How can I use json_encode to return the example JSON?

Barmar
  • 741,623
  • 53
  • 500
  • 612
andrewb
  • 2,995
  • 7
  • 54
  • 95
  • What's the problem? `json_encode()` works with nested arrays. – Barmar Oct 11 '16 at 21:33
  • 1
    I suspect you're really asking how to combine the results from the different queries into a single array, not about how to encode it as JSON. – Barmar Oct 11 '16 at 21:35
  • Yes exactly Barmar – andrewb Oct 11 '16 at 21:35
  • You need to post the code that performs all the queries. For the menus, you use a loop over one query that gets the information for each menuid, then a nested loop that gets the items and pushes it onto the `items` sub-array. Finally, you create `$result = array('success' => true, 'venuedata' => $venuerow, 'menus' => $menus);` Then you encode it. – Barmar Oct 11 '16 at 21:41
  • Possible duplicate of [PHP : Create array for JSON](http://stackoverflow.com/questions/6739871/php-create-array-for-json) – Phil Oct 11 '16 at 21:45

1 Answers1

1

A generalized example assuming the menu items and the menus are connected to each other with a foreign key. Create an array of menus and add for every menu element in the array the menu items.

$arrMenus = array();
$menus = getMenusFromDB();
foreach($menus as $menu) {
    $menuItems = getMenuItemsFromDB($menu["id"]);
    $arrMenuItems = array();
    foreach($menuItems as $menuItem){
         $arrMenuItems []= array(
              "item" => $menuItem["item"],
              "cost" => $menuItem["cost"]
         );
    }

    $arrMenus []= array(
       "menuid" => $menu["id"],
       "menuname" => $menu["menuname"],
       "items" => $arrMenuItems
    );
}

Then create an array with the rest of the information and add the "menus" array as part of the "payload" array:

$obj = array(
    "success" => true,
    "payload" => array(
        "venuedata" => array(
            "id" => "2",
            "name" => "venue name"
        ),
        "menus" => $arrMenus
    )
)

After convert the array via json_encode():

$json = json_encode($obj);
Benjamin
  • 1,067
  • 20
  • 30