PHP:如何检查API中是否存在条目?

时间:2016-10-13 23:15:41

标签: php arrays wikipedia-api

我正在查询Wikipedia API。通常情况下,我会得到以下信息,然后我会提取出来。

array:4 [▼
"pageid" => 13275
"ns" => 0
"title" => "Hungary"
"extract" => """
<p><span></span></p>\n
<p><b>Hungary</b> (<span><span>/<span><span title="/ˈ/ primary stress follows">ˈ</span><span title="'h' in 'hi'">h</span><span title="/ʌ/ short 'u' in 'bud'">ʌ</span><span title="/ŋ/ 'ng' in 'sing'">ŋ</span><span title="'g' in 'guy'">ɡ</span><span title="/ər/ 'er' in 'finger'">ər</span><span title="/i/ 'y' in 'happy'">i</span></span>/</span></span>; Hungarian: <span lang="hu"><i>Magyarország</i></span> <span title="Representation in the International Phonetic Alphabet (IPA)">[ˈmɒɟɒrorsaːɡ]</span>) is a parliamentary constitutional republic in Central Europe. It is situated in the Carpathian Basin and is bordered by Slovakia to the north, Romania to the east, Serbia to the south, Croatia to the southwest, Slovenia to the west, Austria to the northwest, and Ukraine to the northeast. The country's capital and largest city is Budapest. Hungary is a member of the European Union, NATO, the OECD, the Visegrád Group, and the Schengen Area. The official language is Hungarian, which is the most widely spoken non-Indo-European language in Europe.</p>\n

但如果Wiki中不存在该条目,那么我就明白了。

array:3 [▼
"ns" => 0
"title" => "Kisfelegyhaza"
"missing" => ""
]

所以我的问题是如何检查提取是否存在?

我尝试了以下但不起作用。

$wiki_array = The data received from Wiki
if (array_key_exists('extract',$wiki_array)){
 // do something
}

2 个答案:

答案 0 :(得分:1)

$wiki_array = The data received from Wiki
if( isset($wiki_array['extract']) ){
 // do something
}

isset($ var)检查是否设置了var(所以不为null)

答案 1 :(得分:0)

对于遇到同样问题的人,这是我使用的解决方案。

foreach($wiki_array['query']['pages'] as $page){
  if( isset($page['extract']) ){
    echo '<p>';
    echo $page['extract'];
    echo '</p>';
  }
}