0

I want to recursively look through a nested JSON object for keys called 'image', and push their values (URL strings) into another array outside the function.

From other examples and SO questions, I understand that I need to pass a reference to the out-of-scope array variable, but I'm not great with PHP and this doesn't work.

$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 is empty after running this function because the $key are all integers, where as they should actually be strings like 'image', 'title', etc from the JSON object, I thought?

Here is the actual JSON data: https://pastebin.com/Q4J8e1Z6

What have I misunderstood?

Rhecil Codes
  • 511
  • 4
  • 24
  • 1
    Did you mean to use `json_encode`? Are you decoding a JSON stirng? – Nigel Ren May 05 '21 at 17:15
  • What @NigelRen said. Post an example of `$response`. – AbraCadaver May 05 '21 at 17:17
  • Yes. Decoding a JSON string that is an array, from an API. And trying to collect all the values that are associated with 'image' keys – Rhecil Codes May 05 '21 at 17:17
  • the example misses some data to reproduce what you describe. please complete it. an example should contain the minimum set of data and code to illustrate the question, and it should run to do so. – hakre May 05 '21 at 17:19
  • So try decoding the JSON - `$response = json_decode('deeply nested JSON array', true);` – Nigel Ren May 05 '21 at 17:23
  • 1
    Link to actual JSON example: https://pastebin.com/Q4J8e1Z6 @NigelRen Sorry, I did mean json_decode. My bad. – Rhecil Codes May 05 '21 at 17:24

1 Answers1

0

The code you're posted works fine, especially the part about the reference / alias in the use clause of the callback function is absolutely correct.

It's missing the little detail of the second parameter of the json_decode call that was weak in the question (first line of code), it needs to be set to true to have an array all the way down so that a recursive walk on the array traverses all expected fields.

<?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);
hakre
  • 193,403
  • 52
  • 435
  • 836