我需要在页面上显示json_decode的一些数据,但是我收到非法的偏移量错误。
$json = '{"result":{"keyword":"seo",
"cost":0.54,
"concurrency":25,
"found_results":422000000,
"region_queries_count":1900,
"region_queries_count_wide":0,
"region_queries_count_phrase":0,
"types":["related_search","pic"],
"geo_names":[],
"social_domains":["wikipedia","linkedin"],
"right_spelling":null,
"keyword_length":1,
"lang":null,
"keyword_id":"647713",
"suggestions_count":12528,
"keywords_count":1637
},
"status_msg":"OK",
"status_code":200,
"left_lines":99787
}';
$obj = json_decode($json, true);
if (is_array($obj['result'])) {
foreach ($obj['result'] as $keywords) {
echo '<li>Keyword: "'.$keywords['keyword'].'", Adwords CPC: <b>'.$keywords['cost'].'</b> USD, Concurrency: <b>'.$keywords['concurrency'].'</b>, Results: <b>'.$keywords['found_results'].'</b>, Search Volume: <b>'.$keywords['region_queries_count'].'</b>.</li>'.PHP_EOL;
echo '</ol>';
}
}
var_dump($obj) return:
array(4) { ["result"]=> array(16) { ["keyword"]=> string(3) "seo" ["cost"]=> float(0.54) ["concurrency"]=> int(25) ["found_results"]=> int(422000000) ["region_queries_count"]=> int(1900) ["region_queries_count_wide"]=> int(0) ["region_queries_count_phrase"]=> int(0) ["types"]=> array(2) { [0]=> string(14) "related_search" [1]=> string(3) "pic" } ["geo_names"]=> array(0) { } ["social_domains"]=> array(2) { [0]=> string(9) "wikipedia" [1]=> string(8) "linkedin" } ["right_spelling"]=> NULL ["keyword_length"]=> int(1) ["lang"]=> NULL ["keyword_id"]=> string(6) "647713" ["suggestions_count"]=> int(12528) ["keywords_count"]=> int(1637) } ["status_msg"]=> string(2) "OK" ["status_code"]=> int(200) ["left_lines"]=> int(99791) }
答案 0 :(得分:2)
您正在遍历$obj['results']
数组,但这已经是您想要用作关键字的根元素。只需使用它即可:
$keywords = $obj['result'];
echo '<li>Keyword: "'.$keywords['keyword'].'", Adwords CPC: <b>'.$keywords['cost'].'</b> USD, Concurrency: <b>'.$keywords['concurrency'].'</b>, Results: <b>'.$keywords['found_results'].'</b>, Search Volume: <b>'.$keywords['region_queries_count'].'</b>.</li>'.PHP_EOL;
echo '</ol>';
输出:
<li>Keyword: "seo", Adwords CPC: <b>0.54</b> USD, Concurrency: <b>25</b>, Results: <b>422000000</b>, Search Volume: <b>1900</b>.</li> </ol>
答案 1 :(得分:2)
如果可能有多个关键字,则可以将其表示为对象数组。而单个关键字由独立的JSON对象呈现。为了应对这两种情况,此代码将检查它是否是对象数组,如果不是,则将单个条目转换为数组,以便可以使用相同的代码来处理这两个选项...
$obj = json_decode($json, true);
if (isset($obj['result'])) {
// If not a numerically indexed array - convert it
if ( !isset($obj['result'][0])) {
$obj['result'] = [$obj['result']];
}
foreach ($obj['result'] as $keywords) {
echo '<li>Keyword: "'.$keywords['keyword'].'", Adwords CPC: <b>'.$keywords['cost'].'</b> USD, Concurrency: <b>'.$keywords['concurrency'].'</b>, Results: <b>'.$keywords['found_results'].'</b>, Search Volume: <b>'.$keywords['region_queries_count'].'</b>.</li>'.PHP_EOL;
echo '</ol>';
}
}