如何使用JSON_ENCODE合并JSON数据?

时间:2013-11-06 22:35:46

标签: php json

给出以下JSON

$first = array('code'=>'200','message'=>'ok');
{
"code": "200",
"message": "ok"
}


$second = array("user"=>array('fname'=>'Fred','lname'=>'Flintstone','status'=>'1'))
{
"user": [
    {
        "fname": "Fred",
        "lname": "Flintstone",
        "status": "1"
    }
]
}

如何组合这些以获得如下输出。

{
"code": "200",
"message": "ok",
"user": [
    {
        "fname": "Fred",
        "lname": "Flintstone",
        "status": "1"
    }
]
}

3 个答案:

答案 0 :(得分:2)

尝试合并数组

$json = json_encode(array_merge($first, $second));

答案 1 :(得分:0)

也许:

$first = array('code' => '200', 'message' => 'ok');
$second = array('user' => array('fname' => 'Fred', 'lname' => 'Flintstone', 'status' => '1'));

$array = $first + $second; 
$json = json_encode($array);

答案 2 :(得分:0)

使用array_merge您可以组合数组然后对其进行编码:

//arrays
$first = array('code'=>'200','message'=>'ok');
$second = array("user"=>array('fname'=>'Fred','lname'=>'Flintstone','status'=>'1'));

//merging
$merged_arrays = array_merge($first, $second);
print_r($merged_arrays);

//encoding
$json_data = json_encode($merged_arrays);
echo $json_data;