Thursday, 30 August 2018

merge two arrays, find the duplicate key, and update value advertisements

I have two array, where new array locking for duplicate key in old array and replace that value with value from new array,

old array
 Array
(
    [tool_situs] => Array
        (
            [template] => aa
            [title] => bb

        )

 [style] => Array
        (
            [.title] => Array
                (
                    [color] => red
                    [font-size] => 20px

                )

        )

)

and new array
 Array
(
    [tool_situs] => Array
        (
            [title] => ddd
        )

    [style] => Array
        (
            [.title] => Array
                (
                    [color] => #fff

                )

        )

)

I Already Tried using array_merge_recursive() but not replace value of duplicate key, only add new value from new array
 Array
(
    [tool_situs] => Array
        (
            [template] => aa
            [title] => Array
            (
                [0] => aa
                [1] => ddd
            )

        )

 [style] => Array
        (
            [.title] => Array
                (
                    [color] => Array
                    (
                        [0] => red
                        [1] => #fff
                    )
                    [font-size] => 20px

                )

        )

)

in array ebove, tool_situs->title only add new array from new array, also style->.title->color return by add new value from ne array.
help me how to both value of tool_situs->title and style->.title->color replace with value of new array like this
i will be out put like this:
 Array
(
    [tool_situs] => Array
        (
            [template] =>aa
            [title] => ddd
        )

    [style] => Array
        (
            [.title] => Array
                (
                    [color] => #fff
                    [font-size] => 20px
                )

        )

)


As people have stated you want to use array_replace_recursive() Something like the following should work:
$updatedStyles = array_replace_recursive($currentStyles, $newStyles);
This for me would output the following array:
Array
(
    [tool_situs] => Array
        (
            [template] => aa
            [title] => ddd
        )

    [style] => Array
        (
            [title] => Array
                (
                    [color] => blue
                    [font-size] => 20px
                )

        )

)

Can find more information about the function here and you can find a working example here

0 comments:

Post a Comment