How to Modify Json Response get as object to array? - php

this is json response:
{
"level1": {
"level2":
{
"name": "abc",
"age": "19",
"email": "abc#g.com",
"gender": "Female",
"dob": "7 june 1999",
"add": "sdasdadas"
}
}
}
I want to convert JSON response as following way:
{
"level1": {
"level2":
[{
"name": "abc",
"age": "19",
"email": "abc#g.com",
"gender": "Female",
"dob": "7 june 1999",
"add": "sdasdadas"
}]
}
}
I converted my XML response into JSON form and get the object if I have one user details in level2 but I want it in an array in level 2 even have multiple user details or single user details..how can be possible?

Please try this code as #simonecosci mentioned in the comment.
$responseData ='{
"level1": {
"level2":
{
"name": "abc",
"age": "19",
"email": "abc#g.com",
"gender": "Female",
"dob": "7 june 1999",
"add": "sdasdadas"
}
}
}';
$json = json_decode($responseData);
$json->level1->level2 = [$json->level1->level2];
echo '<pre>';
print_r(json_encode($json));
echo '</pre>';
Expected output:
{"level1":{"level2":[{"name":"abc","age":"19","email":"abc#g.com","gender":"Female","dob":"7
june 1999","add":"sdasdadas"}]}}

Related

How to flatten array for json output 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);

PHP Get JSON Values Issue [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 6 years ago.
I'm receiving some JSON POST data from a Webhook into my server. I can get the JSON data as follows:
$orderJSON = file_get_contents('php://input');
which returns this JSON:
{
"order": {
"billing_address": {
"address_1": "76 Pacific Drive",
"address_2": "",
"city": "Bondi",
"company": "Hanson Media",
"country": "AU",
"email": "testing#gmail.com",
"first_name": "Hansel",
"last_name": "Gretten",
"phone": "212 554 7855",
"postcode": "2026",
"state": "NSW"
},
"cart_tax": "3.60",
"completed_at": "2016-12-19T11:07:15Z",
"coupon_lines": [],
"created_at": "2016-12-19T11:07:15Z",
"currency": "AUD",
"customer": {
"billing_address": {
"address_1": "76 Pacific Drive",
"address_2": "",
"city": "Bondi",
"company": "Hanson Media",
"country": "AU",
"email": "testing#gmail.com",
"first_name": "Hansel",
"last_name": "Gretten",
"phone": "212 554 7855",
"postcode": "2026",
"state": "NSW"
},
"email": "testing#gmail.com",
"first_name": "Hansel",
"id": 0,
"last_name": "Gretten",
"shipping_address": {
"address_1": "76 Pacific Drive",
"address_2": "",
"city": "Bondi",
"company": "Hanson Media",
"country": "AU",
"first_name": "Hansel",
"last_name": "Gretten",
"postcode": "2026",
"state": "NSW"
}
},
"fee_lines": [],
"id": 3304,
"is_vat_exempt": false,
"line_items": [
{
"id": 113,
"meta": [],
"name": "Happy Ninja",
"price": "18.00",
"product_id": 37,
"quantity": 2,
"sku": "",
"subtotal": "36.00",
"subtotal_tax": "3.60",
"tax_class": null,
"total": "36.00",
"total_tax": "3.60"
},
{
"id": 114,
"meta": [],
"name": "Water Bottles",
"price": "20.50",
"product_id": 3291,
"quantity": 1,
"sku": "PD885536",
"subtotal": "20.50",
"subtotal_tax": "0.00",
"tax_class": "standard",
"total": "20.50",
"total_tax": "0.00"
}
],
"note": "Call to arrange delivery time",
"order_key": "wc_order_5857bf639d951",
"order_number": 3304,
"payment_details": {
"method_id": "eway",
"method_title": "Credit Card",
"paid": false
},
"shipping_address": {
"address_1": "76 Pacific Drive",
"address_2": "",
"city": "Bondi",
"company": "Hanson Media",
"country": "AU",
"first_name": "Hansel",
"last_name": "Gretten",
"postcode": "2026",
"state": "NSW"
},
"shipping_lines": [
{
"id": 115,
"method_id": "local_pickup:1",
"method_title": "Local Pickup",
"total": "0.00"
}
],
"shipping_methods": "Local Pickup",
"shipping_tax": "0.00",
"status": "pending",
"subtotal": "56.50",
"tax_lines": [
{
"code": "AU-GST-1",
"compound": false,
"id": 116,
"rate_id": "1",
"title": "GST",
"total": "3.60"
}
],
"total": "60.10",
"total_discount": "0.00",
"total_line_items_quantity": 3,
"total_shipping": "0.00",
"total_tax": "3.60",
"updated_at": "2016-12-19T11:07:15Z",
"view_order_url": "https://mywebsite.com/my-account/view-order/3304"
}
}
I now need to get individual elements from the JSON, e.g. I would like to get the id value (3304). I've tried:
$orderID = $orderJSON->id;
and
$orderID = $orderJSON[id];
but this just generates errors like 'Trying to get property of non-object'.
Use the json_decode() function to translate your JSON file into a PHP readable data.
<?php
$json = json_decode($orderJSON);
Once you get your JSON file decoded, you can use the function print_r() to print a nice representation of your datas.
<?php
print_r($orderJSON);
This can help you identify how the file is formed and thus determine all the dimensions you need to display the wanted value.
JSON to nice
Now, if you look closely, you'll see that in order to print your ID, you need to pass through the order dimension.
So you may want to use the syntax $json->order->id to target the wanted ID.
<?php
echo $json->order->id;
Display the ID from JSON
PHP : JSON.
PHP : print_r().
You need to use json_decode() first as I can't see this in your question.
id is under order parent so you need to do sonething like $orderJSON->order->id
You must also check decoded $orderJSON is not empty
Example
$orderJSON = json_decode($orderJSON);
if (empty($orderJSON)) {
throw new RuntimeException('Malformed json');
}
$orderID = $orderJSON->order->id;

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;
}
}

PHP getting values from nested json

I have this json listed below. I was using json_decode to get some of the values. Such as getting the id value:
$decoded_array = json_decode($result, true);
foreach($decoded_array['issue'] as $issues ){
$value[] = $issues["id"];
This method is working for getting the id value, however, I want to get the emailAddress values for both Bob and John. I believe you can get a single value by doing this:
$value[] = $issues["fields"][people][0][emailAddress];
Is it possible to get both email addresses in an efficient manner?
Edited --------
How would you get data with an expanded dataset? Example:
{
"startAt": 0,
"issue": [
{
"id": "51526",
"fields": {
"people": [
{
"name": "bob",
"emailAddress": "bob#gmail.com",
"displayName": "Bob Smith",
},
{
"name": "john",
"emailAddress": "john#gmail.com",
"displayName": "John Smith",
}
],
"skill": {
"name": "artist",
"id": "1"
}
}
},
{
"id": "2005",
"fields": {
"people": [
{
"name": "jake",
"emailAddress": "jake#gmail.com",
"displayName": "Jake Smith",
},
{
"name": "frank",
"emailAddress": "frank#gmail.com",
"displayName": "Frank Smith",
}
],
"skill": {
"name": "writer",
"id": "2"
}
}
}
]
}
I only want to extract the email addresses from both "fields". Is there an easy way to loop through all the "fields" to get "emailAddress" data?
You need to delve deeper into the array.
foreach ($decoded_array['issue'][0]['fields']['people'] as $person) {
echo $person['emailAddress'];
}

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