TheDon TheDon - 6 days ago 6
JSON Question

Loop JSON Data on PHP menu

I want to display our dispensary menu in categorical order. The code provided on the site was this:

<?php
$menuItems = $client->menuItems();
$menuItems = json_decode($menuItems, true);

foreach($menuItems['menu_items'] as $item)
{
print($item['name']);
}
?>


but it displays all our menu. I only want to display the menu that belongs to 'cannabis' category. Below is the json data:



{
"menu_items": [
{
"on_hold":false,
"price": {
"ounce": 250.0,
"quarter": 0.0,
"eighth": 50.0,
"gram": 20.0,
"half": 0.0
},
"category": "Cannabis",
"measurement": "grams",
"sativa":0,
"thc_percent":0,
"cbn":0,
"updated_at":"2010-12-22T23:29:02-07:00",
"amount":3.0,
"cbd":0,
"genetics":"",
"body_html":"",
"created_at":"2010-08-09T15:58:08-07:00",
"name":"Kush",
"indica":0,
"id":3654,
"picture": {
"original":"https://mmjmenu.com/images/attachments_missing/menu_items/images/missing_original.png",
"square":"https://mmjmenu.com/images/attachments_missing/menu_items/images/missing_square.png",
"large":"https://mmjmenu.com/images/attachments_missing/menu_items/images/missing_large.png",
"small":"https://mmjmenu.com/images/attachments_missing/menu_items/images/missing_small.png",
"medium":"https://mmjmenu.com/images/attachments_missing/menu_items/images/missing_medium.png"
}
},
{
"on_hold":false,
"price": {
"ounce": 280.0,
"quarter": 0.0,
"eighth": 55.0,
"gram": 25.0,
"half": 0.0
},
"category": "Cannabis",
"measurement": "grams",
"sativa":0,
"thc_percent":0,
"cbn":0,
"updated_at":"2010-12-22T23:29:02-07:00",
"amount":3.0,
"cbd":0,
"genetics":"",
"body_html":"",
"created_at":"2010-08-09T15:58:08-07:00",
"name":"Blueberry",
"indica":0,
"id":3654,
"picture": {
"original":"https://mmjmenu.com/images/attachments_missing/menu_items/images/missing_original.png",
"square":"https://mmjmenu.com/images/attachments_missing/menu_items/images/missing_square.png",
"large":"https://mmjmenu.com/images/attachments_missing/menu_items/images/missing_large.png",
"small":"https://mmjmenu.com/images/attachments_missing/menu_items/images/missing_small.png",
"medium":"https://mmjmenu.com/images/attachments_missing/menu_items/images/missing_medium.png"
}
}
]
}





i'm using this wrapper https://github.com/nitsujw/mmjmenu-php-client.

Answer

A simple if would suffice.

<?php
        $menuItems = $client->menuItems();
        $menuItems = json_decode($menuItems, true);

        foreach($menuItems['menu_items'] as $item)
        {
           if( $item['category'] == 'Cannabis') {
               print($item['name']);
           }
        }
?>
Comments