user3522457
user3522457

Reputation: 2963

insert an array as an object property (json)

I expect this result

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

where result1 and result2 are the following: $result1

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

$result2

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

I tried

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

but it says Fatal error: Cannot use object of type stdClass as array

Upvotes: 2

Views: 40

Answers (2)

Robotys
Robotys

Reputation: 16

interesting. If the array format is always the same, you can use string functions to change the output too:

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

Does not need to change into array.

Upvotes: 0

You have to do like this..

$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

Upvotes: 2

Related Questions