【问题标题】:foreach() returns only last item with json_decode()foreach() 仅返回带有 json_decode() 的最后一项
【发布时间】: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


【解决方案1】:

每次循环时都会覆盖 $families 变量:

$families = $value['family'];

要将元素添加到数组中,您需要这样做:

$families[] = $value['family'];

这样,每次循环时,$value['family'] 都会添加到您的 $families 数组中。

编辑

foreach 循环之前将$families 变量初始化为空数组也可能很好。因为如果您的 json 中没有任何值,该函数将返回 null

$families = [];
foreach ($items as $key => $value) { ... }

return $families;

【讨论】:

  • 改为使用 array_push($families,$value['family']);
  • $families[] = ...; 对我来说似乎足够了 ;)
  • 是的,这已经足够了,但是有些如何在某些服务器中给出一些奇怪的输出
  • 你有例子吗?你引起了我的兴趣:D
  • 在 nginx 服务器上试试
【解决方案2】:

在你的foreach 每次输出$families

但 return 只返回最后一个$families

【讨论】:

    【解决方案3】:

    这是因为当所有系列都已循环并且 $families 达到最后一个值时,您将在 foreachloop 之外返回字体,因此只返回最后一个值

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-11
      • 2020-06-08
      • 1970-01-01
      • 2023-03-14
      • 2020-05-06
      • 2013-03-15
      • 2021-08-14
      • 2018-01-23
      相关资源
      最近更新 更多