Joining - Merge Multidimentional Array with a key value as identifier in PHP

35 views Asked by At
[{
    "title" = > "CEO",
        "name" = > "George",
        "columns" = > [{
        "display_name" = > "Salary",
        "value" = > "3.85",
    }, {
        "display_name" = > "Bonus",
        "value" = > "994.19",
    }, {
        "display_name" = > "Increment",
        "value" = > "8.15",
    }]
}]


data2 = [{
    "title" = > "CEO",
        "name" = > "George",
        "columns" = > [{
        "display_name" = > "Address",
        "value" = > "Albany",
    }, {
        "display_name" = > "Phone",
        "value" = > "47123",
    }, {
        "display_name" = > "Mobile",
        "value" = > "784123",
    }]
}]

I have the above two arrays, I want to join the values inside columns into one array, if the conditions are met like name = george in both hashes.

The required output is to be like this:

[{
    "title" = > "CEO",
        "name" = > "George",
        "columns" = > [{
        "display_name" = > "Salary",
        "value" = > "3.85",
    }, {
        "display_name" = > "Bonus",    
        "value" = > "994.19",
    }, {
        "display_name" = > "Increment",
        "value" = > "8.15",
    }, {
        "display_name" = > "Address",
        "value" = > "Albany",
    }, {
        "display_name" = > "Phone",
        "value" = > "47123",
    }, {
        "display_name" = > "Mobile",
        "value" = > "784123",
    }]
}]

"name"=>"George" - could be the identifier? or matcher? id name in both is same then dump value of columns into joint array hash.

1

There are 1 answers

0
iam-decoder On

made a function for you:

<?php
    function array_merge_on_key($original, $new, $key){
        if(is_array($original) && is_array($new)){
            $copy_from = array();
            if(array_key_exists($key, $new)){
                if(is_array($new[$key])){
                    $copy_from = $new[$key];
                }
            }
            return is_null($copy_from) ? array_merge($original[$key], $copy_from) : $original;
        }
        return false;
    }