插入一个数组作为对象属性(json)

时间:2014-04-25 04:09:43

标签: php json

我期待这个结果

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

其中result1和result2如下: $ RESULT1

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

$ RESULT2

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

我试过

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

但它表示致命错误:无法使用stdClass类型的对象作为数组

2 个答案:

答案 0 :(得分:2)

你必须这样做..

$result1='[{"uId":"1","firstName":"James","lastName":"Bond"}]';
$result2='[{"task":"teaching"},{"task":"tutoring"}]';
$arr1 = json_decode($result1,true);
$arr2 = json_decode($result2,true);
$arr1[0]['task'] = $arr2;
$finalJSON = json_encode($arr1);
echo $finalJSON;

<强> OUTPUT :

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

Demonstration

答案 1 :(得分:0)

有趣。如果数组格式始终相同,您也可以使用字符串函数来更改输出:

$str = '[{"uId":"1","firstName":"James","lastName":"Bond"}]';
$combined = (trim($str, '}]').',"tasks":[{"task":"teaching"},{"task":"tutoring"}]'.'}]');

无需更改为数组。