How to flatten array for json output php - php

I'm pretty much self teaching myself to code and having a little play with creating a scraper app. I have an array I'm using in an json api but I need to flatten the structure so I can easily consume it elsewhere.
I'm really struggling to fathom out what I need to do here. I've read a load of other questions which are similar requests, but the array formats never match my format so I don't actually know how to tackle this.
This is the current array structure
{
"result": [
{
"Boot buddy": {
"id": "2",
"groupno": "1",
"urlsource": "https://www.amazon.co.uk/Boot-Buddy-fastest-simplest-footwear/dp/B014UPAHO4?pd_rd_wg=lVVK6&pd_rd_r=bf1ba871-fb59-4c66-a146-e94dde7c8e6d&pd_rd_w=gWC2F&ref_=pd_gw_ri&pf_rd_r=W68MX1TXFDDJ8Q8Z08CP&pf_rd_p=cecd4520-32f6-5499-ae19-cd4e83816acd",
"name": "Boot buddy",
"date": "2019-04-14 16:00:29.595,2019-04-14 21:50:31.362,2019-04-14 21:54:11.184",
"price": "£14.99,£14.99,£14.99"
},
"Amazon echo": {
"id": "1",
"groupno": "1",
"urlsource": "https://www.amazon.co.uk/dp/B07CH6JKW3/ref=gw_uk_desk_h1_aucc_cp_mp?pf_rd_p=e4e5a2e6-ddbd-473a-a5fb-e8cc09a11f88&pf_rd_r=1MN25BRXY8YDQ4TBK4X6",
"name": "Amazon echo",
"date": "2019-04-14 16:00:29.595,2019-04-14 21:50:31.362,2019-04-14 21:54:11.184",
"price": "£14.99,£14.99,£14.99"
}
}
]
}
I want to achieve this
{
"result": [
{
"id": "2",
"groupno": "1",
"urlsource": "https://www.amazon.co.uk/Boot-Buddy-fastest-simplest-footwear/dp/B014UPAHO4?pd_rd_wg=lVVK6&pd_rd_r=bf1ba871-fb59-4c66-a146-e94dde7c8e6d&pd_rd_w=gWC2F&ref_=pd_gw_ri&pf_rd_r=W68MX1TXFDDJ8Q8Z08CP&pf_rd_p=cecd4520-32f6-5499-ae19-cd4e83816acd",
"name": "Boot buddy",
"date": "2019-04-14 16:00:29.595,2019-04-14 21:50:31.362,2019-04-14 21:54:11.184",
"price": "£14.99,£14.99,£14.99"
},
{
"id": "1",
"groupno": "1",
"urlsource": "https://www.amazon.co.uk/dp/B07CH6JKW3/ref=gw_uk_desk_h1_aucc_cp_mp?pf_rd_p=e4e5a2e6-ddbd-473a-a5fb-e8cc09a11f88&pf_rd_r=1MN25BRXY8YDQ4TBK4X6",
"name": "Amazon echo",
"date": "2019-04-14 16:00:29.595,2019-04-14 21:50:31.362,2019-04-14 21:54:11.184",
"price": "£14.99,£14.99,£14.99"
}
]
}
This is the code I'm using to generate the array which then gets converted into json for use in the api. I'm iterating over a previous call to the database to merge duplicate records together but keep the unique date and price data. So maybe there's a way to change this code to get the output I'm after?
$records=array();
$records[result]=array();
foreach ($products_arr[records] as $key => $value) {
$hash = $value['name'];
if(isset($result[$hash])){
$result[$hash]['date'] .= ",{$value['date']}";
$result[$hash]['price'] .= ",{$value['price']}";
}else{
$result[$hash] = $value;
}
}
array_push($records[result], $result);
Any help appreciated!!

Like that:
$json=<<<'EOD'
{
"result": [
{
"Boot buddy": {
"id": "2",
"groupno": "1",
"urlsource": "https://www.amazon.co.uk/Boot-Buddy-fastest-simplest-footwear/dp/B014UPAHO4?pd_rd_wg=lVVK6&pd_rd_r=bf1ba871-fb59-4c66-a146-e94dde7c8e6d&pd_rd_w=gWC2F&ref_=pd_gw_ri&pf_rd_r=W68MX1TXFDDJ8Q8Z08CP&pf_rd_p=cecd4520-32f6-5499-ae19-cd4e83816acd",
"name": "Boot buddy",
"date": "2019-04-14 16:00:29.595,2019-04-14 21:50:31.362,2019-04-14 21:54:11.184",
"price": "£14.99,£14.99,£14.99"
},
"Amazon echo": {
"id": "1",
"groupno": "1",
"urlsource": "https://www.amazon.co.uk/dp/B07CH6JKW3/ref=gw_uk_desk_h1_aucc_cp_mp?pf_rd_p=e4e5a2e6-ddbd-473a-a5fb-e8cc09a11f88&pf_rd_r=1MN25BRXY8YDQ4TBK4X6",
"name": "Amazon echo",
"date": "2019-04-14 16:00:29.595,2019-04-14 21:50:31.362,2019-04-14 21:54:11.184",
"price": "£14.99,£14.99,£14.99"
}
}
]
}
EOD;
$arr = json_decode($json, true);
$arr['result'] = array_values($arr['result'][0]);
$result = json_encode($arr);
In the orginal JSON string, the first level of the result key is an array with a single indexed item that gives once decoded to a multidimensionnal array the index 0. To turn all keys contained at this level to indexes, you only need to use the array_values PHP function.

This should work
$json = '{
"result": [
{
"Boot buddy": {
"id": "2",
"groupno": "1",
"urlsource": "https://www.amazon.co.uk/Boot-Buddy-fastest-simplest-footwear/dp/B014UPAHO4?pd_rd_wg=lVVK6&pd_rd_r=bf1ba871-fb59-4c66-a146-e94dde7c8e6d&pd_rd_w=gWC2F&ref_=pd_gw_ri&pf_rd_r=W68MX1TXFDDJ8Q8Z08CP&pf_rd_p=cecd4520-32f6-5499-ae19-cd4e83816acd",
"name": "Boot buddy",
"date": "2019-04-14 16:00:29.595,2019-04-14 21:50:31.362,2019-04-14 21:54:11.184",
"price": "£14.99,£14.99,£14.99"
},
"Amazon echo": {
"id": "1",
"groupno": "1",
"urlsource": "https://www.amazon.co.uk/dp/B07CH6JKW3/ref=gw_uk_desk_h1_aucc_cp_mp?pf_rd_p=e4e5a2e6-ddbd-473a-a5fb-e8cc09a11f88&pf_rd_r=1MN25BRXY8YDQ4TBK4X6",
"name": "Amazon echo",
"date": "2019-04-14 16:00:29.595,2019-04-14 21:50:31.362,2019-04-14 21:54:11.184",
"price": "£14.99,£14.99,£14.99"
}
}
]
}';
$arr = (array) json_decode($json)->result[0];
foreach($arr as $data){
$newArr['result'][] = $data;
}
echo json_encode($newArr);

Related

Get the values in PHP of three objects in Tripadvisor JSON API file

Been struggling with this for too long now, so am kindly asking for your help.
How can I, using PHP, get the values of the text fields in the reviews of which there are three in this JSON file below.
Want to use a foreach loop for this, thanks for helping me out!
{
"address_obj": {
"street1": "Rustenburgerstreet 384",
"street2": null,
"city": "Amsterdam",
"state": "North Holland Province",
"country": "The Netherlands",
"postalcode": "1072 HG",
"address_string": "Rustenburgerstreet 384, 1072 HG Amsterdam The Netherlands"
},
"percent_recommended": null,
"latitude": "52.35162",
"rating": "5.0",
"attraction_types": [
{
"name": "concerts",
"localized_name": "Concerts"
},
{
"name": "blues bars",
"localized_name": "Blues Bars"
},
{
"name": "jazz bars",
"localized_name": "Jazz Bars"
},
{
"name": "bar/ clubs",
"localized_name": "Bars & Clubs"
}
],
"wikipedia_info": null,
"location_id": "3724036",
"review_rating_count": {
"1": "0",
"2": "0",
"3": "1",
"4": "4",
"5": "35"
},
"ranking_data": {
"ranking_string": "#12 of 73 Theater & Concerts in Amsterdam",
"ranking_out_of": "73",
"geo_location_id": "188590",
"ranking": "12",
"geo_location_name": "Amsterdam"
},
"photo_count": "35",
"location_string": "Amsterdam, North Holland Province",
"trip_types": [
{
"name": "business",
"value": "0",
"localized_name": "Business"
},
{
"name": "couples",
"value": "8",
"localized_name": "Couples"
},
{
"name": "solo",
"value": "7",
"localized_name": "Solo travel"
},
{
"name": "family",
"value": "0",
"localized_name": "Family"
},
{
"name": "friends",
"value": "21",
"localized_name": "Friends getaway"
}
],
"web_url": "Attraction_Review-g188590-d3724036-Reviews-m34757-CC_Music_Cafe-Amsterdam_North_Holland_Province.html",
"reviews": [
{
"id": "353301385",
"lang": "en",
"location_id": "3724036",
"published_date": "2016-03-06T05:20:19-0500",
"rating": 5,
"helpful_votes": "0",
"rating_image_url": "img/cdsi/img2/ratings/traveler/s5.0-34757-5.png",
"url": "ShowUserReviews-g188590-d3724036-r353301385-CC_Music_Cafe-Amsterdam_North_Holland_Province.html#review353301385",
"trip_type": "Solo travel",
"travel_date": "2016-02",
"text": "I am a regular visitor of CC Muziekcafé Amsterdam but have felt at home from the very first time. What I like about CC is the atmosphere where great music and hospitality are mixed in the best way...",
"user": {
"username": "Yvon H",
"user_location": {
"name": "Groningen Province, The Netherlands",
"id": "188570"
}
},
"title": "A great place to hear live music and meet all sorts of interesting people, both local and traveling",
"is_machine_translated": false
},
{
"id": "351658487",
"lang": "en",
"location_id": "3724036",
"published_date": "2016-02-28T11:13:12-0500",
"rating": 5,
"helpful_votes": "0",
"rating_image_url": "img/cdsi/img2/ratings/traveler/s5.0-34757-5.png",
"url": "ShowUserReviews-g188590-d3724036-r351658487-CC_Music_Cafe-Amsterdam_North_Holland_Province.html#review351658487",
"trip_type": "Friends getaway",
"travel_date": "2016-02",
"text": "4th time we have been here, another great night at the music cafe, friendly people and a barman who knows how to just put enough swear words in to sound cool",
"user": {
"username": "Francois S",
"user_location": {
"name": "Cardiff, United Kingdom",
"id": "186460"
}
},
"title": "Jazz funk Jam session night Thursday",
"is_machine_translated": false
},
{
"id": "350605184",
"lang": "en",
"location_id": "3724036",
"published_date": "2016-02-24T10:18:57-0500",
"rating": 5,
"helpful_votes": "1",
"rating_image_url": "img/cdsi/img2/ratings/traveler/s5.0-34757-5.png",
"url": "ShowUserReviews-g188590-d3724036-r350605184-CC_Music_Cafe-Amsterdam_North_Holland_Province.html#review350605184",
"trip_type": "Couples",
"travel_date": "2015-09",
"text": "CC muziekcafe is a very cosy place with excellent live music and interaction with the musicians. What really makes the place is the owner Rene who knows a lot about music and now and then even sings...",
"user": {
"username": "ImagineNL",
"user_location": {
"name": "Schagen, The Netherlands",
"id": "609049"
}
},
"title": "Cupid",
"is_machine_translated": false
}
],
You can use this code
<?php
$json = <<<EOF
{
"address_obj": {
"street1": "Rustenburgerstreet 384",
"street2": null,
"city": "Amsterdam",
"state": "North Holland Province",
"country": "The Netherlands",
"postalcode": "1072 HG",
"address_string": "Rustenburgerstreet 384, 1072 HG Amsterdam The Netherlands"
},
"percent_recommended": null,
"latitude": "52.35162",
"rating": "5.0",
"attraction_types": [
{
"name": "concerts",
"localized_name": "Concerts"
},
{
"name": "blues bars",
"localized_name": "Blues Bars"
},
{
"name": "jazz bars",
"localized_name": "Jazz Bars"
},
{
"name": "bar/ clubs",
"localized_name": "Bars & Clubs"
}
],
"wikipedia_info": null,
"location_id": "3724036",
"review_rating_count": {
"1": "0",
"2": "0",
"3": "1",
"4": "4",
"5": "35"
},
"ranking_data": {
"ranking_string": "#12 of 73 Theater & Concerts in Amsterdam",
"ranking_out_of": "73",
"geo_location_id": "188590",
"ranking": "12",
"geo_location_name": "Amsterdam"
},
"photo_count": "35",
"location_string": "Amsterdam, North Holland Province",
"trip_types": [
{
"name": "business",
"value": "0",
"localized_name": "Business"
},
{
"name": "couples",
"value": "8",
"localized_name": "Couples"
},
{
"name": "solo",
"value": "7",
"localized_name": "Solo travel"
},
{
"name": "family",
"value": "0",
"localized_name": "Family"
},
{
"name": "friends",
"value": "21",
"localized_name": "Friends getaway"
}
],
"web_url": "Attraction_Review-g188590-d3724036-Reviews-m34757-CC_Music_Cafe-Amsterdam_North_Holland_Province.html",
"reviews": [
{
"id": "353301385",
"lang": "en",
"location_id": "3724036",
"published_date": "2016-03-06T05:20:19-0500",
"rating": 5,
"helpful_votes": "0",
"rating_image_url": "img/cdsi/img2/ratings/traveler/s5.0-34757-5.png",
"url": "ShowUserReviews-g188590-d3724036-r353301385-CC_Music_Cafe-Amsterdam_North_Holland_Province.html#review353301385",
"trip_type": "Solo travel",
"travel_date": "2016-02",
"text": "I am a regular visitor of CC Muziekcafé Amsterdam but have felt at home from the very first time. What I like about CC is the atmosphere where great music and hospitality are mixed in the best way...",
"user": {
"username": "Yvon H",
"user_location": {
"name": "Groningen Province, The Netherlands",
"id": "188570"
}
},
"title": "A great place to hear live music and meet all sorts of interesting people, both local and traveling",
"is_machine_translated": false
},
{
"id": "351658487",
"lang": "en",
"location_id": "3724036",
"published_date": "2016-02-28T11:13:12-0500",
"rating": 5,
"helpful_votes": "0",
"rating_image_url": "img/cdsi/img2/ratings/traveler/s5.0-34757-5.png",
"url": "ShowUserReviews-g188590-d3724036-r351658487-CC_Music_Cafe-Amsterdam_North_Holland_Province.html#review351658487",
"trip_type": "Friends getaway",
"travel_date": "2016-02",
"text": "4th time we have been here, another great night at the music cafe, friendly people and a barman who knows how to just put enough swear words in to sound cool",
"user": {
"username": "Francois S",
"user_location": {
"name": "Cardiff, United Kingdom",
"id": "186460"
}
},
"title": "Jazz funk Jam session night Thursday",
"is_machine_translated": false
},
{
"id": "350605184",
"lang": "en",
"location_id": "3724036",
"published_date": "2016-02-24T10:18:57-0500",
"rating": 5,
"helpful_votes": "1",
"rating_image_url": "img/cdsi/img2/ratings/traveler/s5.0-34757-5.png",
"url": "ShowUserReviews-g188590-d3724036-r350605184-CC_Music_Cafe-Amsterdam_North_Holland_Province.html#review350605184",
"trip_type": "Couples",
"travel_date": "2015-09",
"text": "CC muziekcafe is a very cosy place with excellent live music and interaction with the musicians. What really makes the place is the owner Rene who knows a lot about music and now and then even sings...",
"user": {
"username": "ImagineNL",
"user_location": {
"name": "Schagen, The Netherlands",
"id": "609049"
}
},
"title": "Cupid",
"is_machine_translated": false
}
]
}
EOF;
$array = json_decode($json, true);
$texts = array_map(
function($item) {
return $item['text'];
}, $array['reviews']
);
It doesn't seem like you need a foreach to fetch the reviews element. Not sure if I understood your question correct, but did you want something like this:
$assoc_json = json_decode($your_json, true);
var_dump($assoc_json['reviews']);
The above turns your json into an associative array, and just access the review element.
A simple, naive approach would be:
//Loads your json file 'tripadvisor' into jsonString
$jsonString = file_get_contents("/tripadvisor.json");
//Turns your string into an associative array
$tripJsonAssoc = json_decode($jsonString, true);
//Iterate through each review and store it in result
$result = array();
foreach($tripJsonAssoc['reviews'] as $review) {
$result[] = array('text' => $review['text'],
'rating' => $review['rating']);
}
//Do what you need to do with result
//...
Or you can just do your own stuff inside the foreach loop.
This answer gives you another way (more elegant) to create the 'result' array, but since you asked for a 'foreach', I thought I would add my 5 cents.

PHP loop through data from JSON string

I want to get ItemCategory->id's for each Item->id
How can I do it in the best way?
Here is a part of JSON data item
"6": {
"Item": {
"id": "6",
"name": "test",
"description": "description",
},
"ItemThumbnail": null,
"ItemCategory": {
"3": {
"id": "3",
"name": "name",
"status": "active",
"date_created": "2015-07-07 11:23:52",
"date_updated": "0000-00-00 00:00:00",
},
"4": {
"id": "4",
"name": "name",
"status": "active",
"date_created": "2015-07-07 11:23:52",
"date_updated": "0000-00-00 00:00:00",
}
},
"ItemGroup": []
},
You can convert your json string to a PHP array using $array = json_decode($str, true);, then loop your array and extract the information you need.
See http://php.net/manual/en/function.json-decode.php for more detail on json_decode
After json decode use this.
foreach($Item as $Items)
{
$ItemCategory = $Items->ItemCategory;
foreach($ItemCategory as $ItemCategorys)
{
echo $ItemCategorys->id;
}
}

How to remove first array name from json

I'm Getting values like this in JSON format -
{
"comments": [{
"name": "ABC",
"desc": "Hello...",
"values": [{
"status": "fine",
"label": ""
}]
}, {
"name": "XYZ",
"desc": "Good Morning..",
"values": [{
"status": "fine",
"label": "happy"
}]
}]
}
But i don't want first array name means i need result like this -
[{
"name": "ABC",
"desc": "Hello...",
"values": [{
"status": "fine",
"label": ""
}]
}, {
"name": "XYZ",
"desc": "Good Morning..",
"values": [{
"status": "fine",
"label": "happy"
}]
}]
Need a help...
Do like this...
<?php
$json='{
"comments": [{
"name": "ABC",
"desc": "Hello...",
"values": [{
"status": "fine",
"label": ""
}]
}, {
"name": "XYZ",
"desc": "Good Morning..",
"values": [{
"status": "fine",
"label": "happy"
}]
}]
}';
$arr=json_decode($json,1);
echo json_encode($arr['comments']);
OUTPUT :
[{"name":"ABC","desc":"Hello...","values":[{"status":"fine","label":""}]},{"name":"XYZ","desc":"Good Morning..","values":[{"status":"fine","label":"happy"}]}]
Try this:
$data = '[{
"name": "ABC",
"desc": "Hello...",
"values": [{
"status": "fine",
"label": ""
}]
}, {
"name": "XYZ",
"desc": "Good Morning..",
"values": [{
"status": "fine",
"label": "happy"
}]
}]';
$return = json_decode($data, true);
foreach ($return as $key => $value){
unset($return[$key]['name']);
}
echo '<pre>';
print_r($return);
echo '</pre>';

Issue with json_decode and json_encode - it adds keys to original JSON

I have this JSON string:
{
"product": [
{
"id": "1",
"title": "producta",
"size": "50",
"weight": "1000",
"price": "30",
"quantity": "100",
"cartID": "1"
},
{
"id": "1",
"title": "producta",
"size": "50",
"weight": "1000",
"price": "30",
"quantity": "100",
"cartID": "2"
}
]
}
When I use the PHP function json_decode($products, true), and then I re-encode it using json_encode($products), the string becomes this:
{
"product": {
"1": {
"id": "2",
"title": "producta",
"size": "50",
"weight": "1000",
"price": "30",
"quantity": "100",
"cartID": "2"
},
"2": {
"id": "1",
"title": "producta",
"size": "50",
"weight": "1000",
"price": "30",
"quantity": "100",
"cartID": "3"
}
}
}
After decoding and re-encoding, it adds a key to every "product"
Is there a way around this?
Posting this here since it'd be too ugly in a comment, but this is what I get on PHP 5.3.6 after doing a echo json_encode(json_decode('...your json...', true));:
{"product": [
{"id":"1","title":"producta","size":"50","weight":"1000","price":"30","quantity":"100","cartID":"1"},
{"id":"1","title":"producta","size":"50","weight":"1000","price":"30","quantity":"100","cartID":"2"}
]}
Note the lack of extra keys. Are you doing any manipulations on the decoed array before re-encoding?
You are probably using mysqli_fetch_array instead of mysqli_fetch_assoc. Meaning u are json decoding a key arreay instead of an associative array

PHP Troubles with converting from JSON to stdClass, making changes, and then converting back to JSON

So, in the very beginning, before the send_sms.php is loaded, I have this Json stored in a database:
{
"chats": {
"chat": [{
"id": "1",
"name": "Ethan Wilberforce",
"messages": {
"message": [{
"id": "1",
"name": "Ethan Wilberforce",
"text": "Hello how are you doing",
"time": "4:41"
}, {
"id": "2",
"name": "Qasim Iqbal",
"text": "Not bad. How about you?",
"time": "4:42"
}, {
"id": "3",
"name": "Ethan Wilberforce",
"text": "I'm not too bad myself.",
"time": "4:43"
}]
}
}, {
"id": "2",
"name": "Geoff Vahaaho",
"messages": {
"message": [{
"id": "1",
"name": "Geoff Vahaaho",
"text": "Hello how are you doing",
"time": "4:41"
}, {
"id": "2",
"name": "Qasim Iqbal",
"text": "Not bad. How about you?",
"time": "4:42"
}, {
"id": "3",
"name": "Geoff Vahaaho",
"text": "I'm not too bad myself.",
"time": "4:43"
}, {
"id": "4",
"name": "Qasim Iqbal",
"text": "Nice.",
"time": "4:43"
}]
}
}]
}
}
The Json is completely valid, no errors. It is storing two chats, with messages in them.
Now, here is the PHP code that alters the Json:
$data = $user->data;
$parsed_data = json_decode($data);
...
for($i = 0, $size = sizeof($parsed_data->chats->chat); $i < $size; ++$i) {
if($parsed_data->chats->chat[$i]->name == $to) {
$found = true;
$parsed_data->chats->chat[$i]->messages->message[sizeof($parsed_data->chats->chat[$i]->messages->message)] = new stdClass;
$parsed_data->chats->chat[$i]->messages->message[sizeof($parsed_data->chats->chat[$i]->messages->message)]->id = sizeof($parsed_data->chats->chat[$i]->messages->message);
$parsed_data->chats->chat[$i]->messages->message[sizeof($parsed_data->chats->chat[$i]->messages->message)]->name = $user->name;
$parsed_data->chats->chat[$i]->messages->message[sizeof($parsed_data->chats->chat[$i]->messages->message)]->text = $message;
$parsed_data->chats->chat[$i]->messages->message[sizeof($parsed_data->chats->chat[$i]->messages->message)]->time = $time;
echo "done. ";
break;
}
}
What I intend this to do is, to add another stdClass object in the "message" array of the chat. So I basically do just that, hoping it will work.
Now, it works, kind of, but here is the new Json after we json_encode it:
{
"chats": {
"chat": [{
"id": "1",
"name": "Ethan Wilberforce",
"messages": {
"message": [{
"id": "1",
"name": "Ethan Wilberforce",
"text": "Hello how are you doing",
"time": "4:41"
}, {
"id": "2",
"name": "Qasim Iqbal",
"text": "Not bad. How about you?",
"time": "4:42"
}, {
"id": "3",
"name": "Ethan Wilberforce",
"text": "I'm not too bad myself.",
"time": "4:43"
}, {}, {
"id": 4
}, {
"name": "Qasim Iqbal"
}, {
"text": "Hello i am testing"
}, {
"time": 1326066200
}]
}
}, {
"id": "2",
"name": "Geoff Vahaaho",
"messages": {
"message": [{
"id": "1",
"name": "Geoff Vahaaho",
"text": "Hello how are you doing",
"time": "4:41"
}, {
"id": "2",
"name": "Qasim Iqbal",
"text": "Not bad. How about you?",
"time": "4:42"
}, {
"id": "3",
"name": "Geoff Vahaaho",
"text": "I'm not too bad myself.",
"time": "4:43"
}, {
"id": "4",
"name": "Qasim Iqbal",
"text": "Nice.",
"time": "4:43"
}]
}
}]
}
}
You will notice it was indeed added in the "Ethan Wilberforce" chat, but each string in the stdClass was converted to its own array item in the "message" array. How could I fix this problem? Many thanks.
Your problem is this:
$parsed_data->chats->chat[$i]->messages->message[sizeof($parsed_data->chats->chat[$i]->messages->message)] = new stdClass;
$parsed_data->chats->chat[$i]->messages->message[sizeof($parsed_data->chats->chat[$i]->messages->message)]->id = sizeof($parsed_data->chats->chat[$i]->messages->message);
It basically amounts to:
$array[$last] = new stdClass();
$array[$last+1] = "id";
$array[$last+2] = "name";
You keep appending new arrays/objects, because you use sizeof(...) which always becomes one larger than the previous line. It's not the last index, but the size. Which is $lastindex+1.
What you should be doing anyway, is not using an object, but just appending an array, and with all its attributes at once:
$parsed_data->chats->chat[$i]->messages->message[] = array(
"id" => ...,
"name" => ...,
"time" => ...,
);
When you encode that associative array back into JSON it will also become a normal {...} JSON object group.

Categories