2016-11-23 30 views
-1

我正在使用基於API的此工具http://apps.evemilano.com/entities/。 這是我得到的JSON文件。並非每個「itemListElement」都具有相同的細節級別。我想用「描述」來計算所有ItemList。如何只計算JSON中的現有元素

{ 
    "@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 
    } 
    ] 
} 

不是每個實體都有一個描述,有3個實體,只有2個「描述」。我如何計算只有現有的「描述」使用PHP?我需要打印「2」:)

謝謝。

+0

歡迎StackOverflow上。請爲您的問題添加更多相關標籤。您可能需要使用特定編程語言的解決方案:將其添加爲標籤。 – Codo

+0

你對哪種語言感興趣?你可能會得到不同的答案每個編程語言或庫 – Tudor

+0

對不起,PHP語言 –

回答

0

您可以json_decode解碼您的JSON有效載荷:

$data = json_decode($json, true); 

然後你可以遍歷$data['itemListElement']並檢查是否$item['result']['description']定義:

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

echo $count; // 2 
+0

超級,非常感謝你! –