【发布时间】:2019-08-01 10:37:33
【问题描述】:
尝试使用 foreach() 循环从解码的 JSON 返回 Google 字体系列,
但我只得到最后一个家庭,而不是全部。
我一直在苦苦挣扎,在谷歌上搜索,尝试了所有我知道/找到的东西,但没有结果!
这是代码,我在 WordPress 中使用它。
<?php
/**
* Get Google Fonts.
*/
public function get_google_fonts() {
$google_api = 'https://www.googleapis.com/webfonts/v1/webfonts?key=MY-API-KEY';
$font_content = wp_remote_get( $google_api, array( 'sslverify' => false ) );
$content = json_decode( $font_content['body'], true );
$items = $content['items']; // I've tried (array) $content['items'];
// I've tried $i = 0;
// I've tried $families = array();
foreach ( $items as $key => $value ) {
$families = $value['family'];
BugFu::log( $families, false ); // Correct returning all families.
// I've tried $i++;
}
return array( $families ); // OR return $families; Returning last family.
}
非常感谢任何帮助。
提前感谢您的时间:)
【问题讨论】:
-
还包括 JSON 响应,以便人们了解结构。
-
你必须将你的变量作为一个数组你正在做的是你在 foreach 循环中记录输出并一遍又一遍地覆盖变量尝试函数 array_push($families,$value['family' ]);
-
@AbdulQuadirDewaswala 非常感谢您指出这一点以及 array_push() 方法。
标签: php arrays json wordpress multidimensional-array