Search code examples
phprecursionarray-walk

Put values in array outside of array_walk_recursive()


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?


Solution

  • 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);