-1

How to replace values in a nested array with array_walk?

This is my array,

$item = array(
    "id" => "2",
    "title" => "parent 2",
    "children" => array (
           "id" => "4",
           "title" => "children 1"
        )
);

//replacement array:
$replace = [
  '2' => 'foo',
  '4' => 'bar',
  '7' => 'baz'
];

My working function,

function myfunction(&$value,$key,$replace)
{   

    if(isset($replace[$key]))
    {
       $value = $replace[$key];
    }

    if(is_array($key))
    {
        array_walk($value,"myfunction",$replace);
    }
}

array_walk($item,"myfunction",$replace);

print_r($item);

result,

Array
(
    [id] => 2
    [title] => parent 2
    [children] => Array
        (
            [id] => 4
            [title] => children 1
        )

)

The result I'm after,

Array
(
    [id] => 2
    [title] => foo
    [children] => Array
        (
            [id] => 4
            [title] => bar
        )

)

2 Answers 2

2

This recursive function may help you

function replace($item,$replace)
{
    foreach ($replace as $key => $value) 
    {
        if($item["id"]==$key)
            $item["title"] = $value;
        if(isset($item['children']))
            $item['children'] = replace($item['children'],$replace);
    }
    return $item;
}

it doesn't modify $item, it returns it modified, so you need to call it like this

$item = replace($item,$replace);

In order to make your function modify the argument $item, just pass it by reference like this :

function replace(&$item,$replace)
{
    foreach ($replace as $key => $value) 
    {
        if($item["id"]==$key)
            $item["title"] = $value;
        if(isset($item['children']))
            replace($item['children'],$replace);
    }
}

In this case you just need to call the function like this :

replace($item,$replace);
print_r($item);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! So I don't need array_walk in this case then?
What should $item and $replace be in your final function?
0

Try this function :

    function replaceKey($subject, $newKey, $oldKey) {

    if (!is_array($subject)) return $subject;

    $newArray = array(); // empty array to hold copy of subject
    foreach ($subject as $key => $value) {

        // replace the key with the new key only if it is the old key
        $key = ($key === $oldKey) ? $newKey : $key;

        // add the value with the recursive call
        $newArray[$key] = $this->replaceKey($value, $newKey, $oldKey);
    }
    return $newArray;
}

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.