在PHP中合并两个复杂的对象

前端之家收集整理的这篇文章主要介绍了在PHP中合并两个复杂的对象前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有两个从 JSON转换的数据对象.两者都非常复杂,我想以类似的方式将它们合并到jQuery将如何使用extends合并两个对象.

JSON 1:

{
    ...
    "blah":
    {
        "params":
        {
            "foo":
            {
                "default": "bar","misc": "0",...
            },...
        },...
    },...
}

JSON 2:

{
    ...
    "blah":
    {
        "params":
        {
            "foo":
            {
                "value": "val","misc": "1",...
}

合并成

{
    ...
    "blah":
    {
        "params":
        {
            "foo":
            {
                "default": "bar","value": "val",...
}

使用PHP对象来处理这个问题的最好方法是什么?

将每个JSON字符串解码为关联数组,合并结果并进行重新编码
$a1 = json_decode( $json1,true );
$a2 = json_decode( $json2,true );

$res = array_merge_recursive( $a1,$a2 );

$resJson = json_encode( $res );

更新:
如果您具有特定的合并要求,则需要编写自己的合并功能.
我在下面写了一个符合您的要求的问题.
如果您还没有提到其他要求,则可能需要进行调整.

<?PHP

$json1 = '
{
    "blah":
    {
        "params":
        {
            "foo":
            {
                "default": "bar","misc": "0"
            }
        },"lost":
        {
            "one": "hat","two": "cat"
        }
    }
}';

$json2 = '
{
    "blah":
    {
        "lost": "gone","params":
        {
            "foo":
            {
                "value": "val","misc": "1"
            }
        }
    },"num_array": [12,52,38]
}';


$a1 = json_decode( $json1,true );


/*
 * Recursive function that merges two associative arrays
 * - Unlike array_merge_recursive,a differing value for a key
 *   overwrites that key rather than creating an array with both values
 * - A scalar value will overwrite an array value
 */
function my_merge( $arr1,$arr2 )
{
    $keys = array_keys( $arr2 );
    foreach( $keys as $key ) {
        if( isset( $arr1[$key] ) 
            && is_array( $arr1[$key] ) 
            && is_array( $arr2[$key] ) 
        ) {
            $arr1[$key] = my_merge( $arr1[$key],$arr2[$key] );
        } else {
            $arr1[$key] = $arr2[$key];
        }
    }
    return $arr1;
}


$a3 = my_merge( $a1,$a2);
$json3 = json_encode( $a3 );
echo( $json3 );

/*
{
    "blah":
    {
        "params":
        {
            "foo":
            {
                "default": "bar","misc":    "1","value":   "val"
            }
        },"lost": "gone"
    },38]
}
*/

猜你在找的PHP相关文章