1

Im trying to overlay, or replace if you will, an array with another array. For this i was trying the array_replace_recursive function but i get unwanted behaviour that i cannot seem to clear out.

I have two arrays:

The original array:

[test] => Array
            [me] => Array
                    [0] => test
                    [1] => me
                    [2] => now
            [me2] => Array
                    [0] => test
                    [1] => me
                    [2] => now

And the array i want to replace

[test] => Array
            [me2] => Array
                    [name] => firstname
                    [last] => lastname

After using array_replace_recursive($first_array, $second_array) i get the following output:

 [test] => Array
            [me] => Array
                    [0] => test
                    [1] => me
                    [2] => now
            [me2] => Array
                    [0] => test <-- this needs to be overwritten not appended
                    [1] => me <-- this needs to be overwritten not appended
                    [2] => now <-- this needs to be overwritten not appended
                    [name] => firstname
                    [last] => lastname

I really need the ['test']['me2'] value to be overwritten en not appended. So the 0,1,2 keys should be gone. Can someone point me in the right direction here?

5
  • I would be helped if i can somehow delete a value based on an array of keys, something i am trying right now but at the moment without result. Something in the line of: ``` $first_array = some_function_to_remove($keys = ['test','me2'], $first_array); array_replace_recursive($first_array, $second_array); ```
    – DJQ
    Mar 19, 2020 at 20:41
  • Why are you using array_replace_recursive? Seems like array_replace would be the choice.
    – El_Vanja
    Mar 19, 2020 at 20:58
  • With array_replace($first_array, $second_array) i will only get the array back that i give as second argument, so $second_array.
    – DJQ
    Mar 19, 2020 at 21:00
  • 1
    Ahh, I tested it the wrong way, forgot the top level key... nevermind.
    – El_Vanja
    Mar 19, 2020 at 21:01
  • 1
    Is the depth of your array fixed?
    – El_Vanja
    Mar 19, 2020 at 21:04

2 Answers 2

1

You probably have to write your own function that does the replacement in the way you see fit. I think it should:

  • accept two arrays ($a,$b) as it's paramaters
  • if $a[KEY] is an array and $b[KEY] is not set, keep $a[KEY]
  • if $a[KEY] is an array and $b[KEY] is an array, call this method w/ ($a[KEY] & $b[KEY])
  • if $a's children are NOT arrays and $b has children, replace $a with $b

Or something like that... I had a hard time conceptualizing what exactly you need and in writing a function for it, there were edge cases I realized could come up in more complex arrays.

So I wrote this function & the test. I've only tested it with the sample arrays you gave, but it gives the correct output for those. It might be buggy if you add another layer to the array or if there's an array in there that has some children who are arrays and some children who are not arrays.

<?php

function recurseReplace($a,$b){
    $ret = [];
    foreach ($a as $key=>$value){
        if (!isset($b[$key])&&is_array($value)){
            $ret[$key] = $value;
            continue;
        } 
        if (is_array($value)&&isset($b[$key])&&is_array($b[$key])){
            $ret[$key] = recurseReplace($value,$b[$key]);
            continue;
        }
    }
    if (count($ret)==0){
        foreach ($b as $key=>$value){
            $ret[$key] = $value;
        }
    }
    return $ret;
}

$a = [
    "test" => [
        "me"=>['test','me','now'],
        "me2"=>["test",'me','now']
        ]
    ];

$b = [
    "test" => [
        "me2"=>["name"=>'firstname',"last"=>"lastname"]
        ]
    ];

$desired = [
    "test" => [
        "me"=>['test','me','now'],
        "me2"=>["name"=>'firstname',"last"=>"lastname"]
        ]
    ];

$final = recurseReplace($a,$b);
echo "\n\n-----final output::---\n\n";

print_r($final);
echo "\n\n-----desired::---\n\n";

print_r($desired);
1

Reed,

Thank you this worked for me.. but i got inspired by your code and started to improve on it. For other people who need something like this:

    function conf_get($paths, $array) {
        $paths = !is_array($paths) ? [] : $paths;
        foreach ($paths as $path)
            $array = $array[$path];
        return $array;
    }
    function conf_set($paths, $value, $array) {
        $array = !is_array($array) ? [] : $paths; // Initialize array if $array not set
        $result = &$array;
        foreach ($paths as $i => $path) {
            if ($i < count($paths) - 1) {
                if (!isset($result[$path]))
                    $result[$path] = [];
                $result = &$result[$path];
            } else
                $result[$path] = $value;
        }
        return $result;
    }

    $config = [];
    $config ['test']['me'] = ['test', 'me', 'now'];
    $config ['test']['me2'] = ['test', 'me', 'now'];

echo "\n INITIAL CONFIG"; 
print_r($config );
echo "\n GET PATH test"; 
print_r(conf_get('test', $config));
echo "\n GET PATH test,me1" ;
print_r(conf_get(['test', 'me2'], $config);
echo "\n REPLACE PATH test,me2 with new array" ;
print_r(conf_set(['test', 'me2'], ['name' => 'firstname', 'last' => 'lastname'], $config), "");
echo "\n ADD PATH test,me6 with new array";
print_r(conf_set(['test', 'me6'], ['name' => 'firstname', 'last' => 'lastname'], $config));

Result:


[INITIAL CONFIG]
    [test] => Array
            [me] => Array
                    [0] => test
                    [1] => me
                    [2] => now
            [me2] => Array
                    [0] => test
                    [1] => me
                    [2] => now

[GET PATH test]
    [test] => Array
            [me] => Array
                    [0] => test
                    [1] => me
                    [2] => now
            [me2] => Array
                    [0] => test
                    [1] => me
                    [2] => now

[GET PATH test,me1]
    [0] => test
    [1] => me
    [2] => now

[REPLACE PATH test,me2 with new array]
    [me2] => Array
            [name] => firstname
            [last] => lastname

[ADD PATH test,me6 with new array]
    [me6] => Array
            [name] => firstname
            [last] => lastname

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.