连接 - 在PHP中使用键值合并Multidimentional Array作为标识符

时间:2015-06-25 16:01:02

标签: php arrays multidimensional-array array-merge

[{
    "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",
    }]
}]

我有上面两个数组,我想将columns内的值加入到一个数组中,如果满足条件,就像两个哈希中的name = george一样。

所需的输出如下:

[{
    "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" - 可能是标识符?还是匹配?两者中的id名称相同,然后将列的值转储到联合数组哈希中。

1 个答案:

答案 0 :(得分:0)

为你做了一个功能:

<?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;
    }