0

I am using array_walk_recursive with a callback function to search within a nested array for specified key:

array_walk_recursive($array, array($this, 'walk_array'), $key);

Here is the callback function:

function walk_array($value, $key, $userdata = '')
{
    if ($key === $userdata)
    {
        self::$items_array[$key] = $value;
        echo $value . "<br />\n";
    }
}

The problem is that I can not find a way to store/return the found elements from the callback function even though I am using static variable $items_array but it always contains the last item processed by the array_walk_recursive. On the other hand, if I echo the found elements from callback function:

echo $value . "<br />\n";

All found elements are echoed fine.

How do I return or store the found elements from the callback function?

0

1 Answer 1

3

If $key is going to correspond to multiple values in the nested arrays that you walk through, your $item_arrays should have its own array for that key. Otherwise, all you're really doing is overwriting self::$items_array[$key] with every value that comes by.

Try this:

self::$items_array[$key][] = $value;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.