将数组合并到另一个数组时的json格式

时间:2014-04-25 03:37:17

标签: javascript php json

$ result1 value

[{"uId":"1","firstName":"James","lastName":"Bond"}]

$ result2 value

[{"task":"teaching"},{"task":"tutoring"}]

我希望将数组$ result2放在$ result1中

$result1['task'] = $result2;
echo json_encode($result1);

我得到了:

{"0":{"uId":"1","firstName":"James","lastName":"Bond"},"task":[{"task":"teaching"},{"task":"tutoring"}]}

我希望它是这样的?

[
    {
        "uId": "1",
        "firstName": "James",
        "lastName": "Bond",
        "task": [
            {
                "task": "teaching"
            },
            {
                "task": "tutoring"
            }
        ]
    }
]

1 个答案:

答案 0 :(得分:0)

因此,您必须将'task'添加到$result1的第一个元素。

$result1[0]['task'] = $result2;
echo json_encode($result1);

如果$result1$result2都是stdClass而不是数组,请尝试:

$result1 = (array)$result1;
$result2 = (array)$result2;

$result1[0]['task'] = $result2;
echo json_encode($result1);