【问题标题】:Put values in array outside of array_walk_recursive() [duplicate]将值放在array_walk_recursive()之外的数组中[重复]
【发布时间】:2021-07-28 01:02:31
【问题描述】:

我想递归地在嵌套的 JSON 对象中查找名为“image”的键,并将它们的值(URL 字符串)推送到函数外部的另一个数组中。

从其他示例和 SO 问题中,我了解到我需要传递对范围外数组变量的引用,但我对 PHP 不是很好,这不起作用。

$response = json_decode('deeply nested JSON array from link below');

$preload = [];

array_walk_recursive($response, function($item, $key) use (&$preload) {
  if ($key === 'image') {
    array_push($preload, $item);
  }
});

$preload 在运行此函数后为空,因为$key 都是整数,而我认为它们实际上应该是 JSON 对象中的“图像”、“标题”等字符串?

这是实际的 JSON 数据:https://pastebin.com/Q4J8e1Z6

我误解了什么?

【问题讨论】:

  • 您的意思是使用json_encode 吗?您在解码 JSON 搅拌吗?
  • @NigelRen 说了什么。发布$response 的示例。
  • 是的。从 API 解码作为数组的 JSON 字符串。并尝试收集与“图像”键关联的所有值
  • 该示例遗漏了一些数据来重现您所描述的内容。请完成它。一个示例应该包含最少的数据和代码集来说明问题,并且应该运行它。
  • 链接到实际的 JSON 示例:pastebin.com/Q4J8e1Z6@NigelRen 抱歉,我的意思是 json_decode。我的错。

标签: php recursion array-walk


【解决方案1】:

您发布的代码运行良好,尤其是回调函数的use子句中关于引用/别名的部分是绝对正确的。

它缺少问题中弱的 json_decode 调用的第二个参数的小细节(第一行代码),它需要设置为 true 才能有一个数组一直向下,以便递归遍历数组遍历所有期望的字段。

<?php

$buffer = file_get_contents('https://pastebin.com/raw/Q4J8e1Z6');
$response = json_decode($buffer, true);

$preload = [];

array_walk_recursive($response, function($item, $key) use (&$preload) {
    if ($key === 'image') {
        $preload[] = $item;
    }
});

print_r($preload);

【讨论】:

    猜你喜欢
    • 2012-08-27
    • 1970-01-01
    • 2014-08-24
    • 2020-12-25
    • 2022-08-02
    • 2013-08-25
    • 2016-05-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多