EVE Milano EVE Milano - 12 days ago 5
JSON Question

How to count only existing elements inside JSON

I'm working on this tool http://apps.evemilano.com/entities/ based on API.
This is the JSON file I get. Not every "itemListElement" has the same level of detail. I want to count all ItemList with a "description".

{
"@context": {
"@vocab": "http://schema.org/",
"goog": "http://schema.googleapis.com/",
"EntitySearchResult": "goog:EntitySearchResult",
"detailedDescription": "goog:detailedDescription",
"resultScore": "goog:resultScore",
"kg": "http://g.co/kg"
},
"@type": "ItemList",
"itemListElement": [
{
"@type": "EntitySearchResult",
"result": {
"@id": "kg:/g/121gpq6x",
"name": "Calogero Angelo Sacheli",
"@type": [
"Person",
"Thing"
],
"description": "Author"
},
"resultScore": 7.989742
},
{
"@type": "EntitySearchResult",
"result": {
"@id": "kg:/m/0z3rcdq",
"name": "Giovanni Sacheli",
"@type": [
"Thing",
"Person"
],
"url": "http://www.evemilano.com/"
},
"resultScore": 6.925036
},
{
"@type": "EntitySearchResult",
"result": {
"@id": "kg:/m/07zy0l",
"name": "Quarterback Princess",
"@type": [
"Movie",
"Thing"
],
"description": "1983 film",
"detailedDescription": {
"articleBody": "Quarterback Princess is a 1983 American made-for-television fact-based sports drama film by 20th Century Fox that chronicles the courage and determination of a teenage girl who struggles against sexism and fights to play on her high school football team. ",
"url": "https://en.wikipedia.org/wiki/Quarterback_Princess",
"license": "https://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License"
}
},
"resultScore": 0.945328
}
]
}


Not every entities has one description, there are 3 entities and only 2 "description". How can i COUNT only existing "description" using PHP? I need to print "2" :)

Thank you.

Answer

You can decode your json payload with json_decode:

$data = json_decode($json, true);

Then you can iterate $data['itemListElement'] and check if $item['result']['description'] is defined:

$count = array_reduce($data['itemListElement'], function($count, $item) {
    return isset($item['result']['description']) ? ++$count : $count;
}, 0);

echo $count; // 2