How to set name to JSON object in laravel as I want to display for a plugin in Vue js for image gallery. Whenever I pass data I Got this error : Expected Object, got Array.
{
"normal_size": [
{
"id": 1,
"image": "MICMIMC30651-6.jpg",
"url": "http://localhost:8000/images/product/preview/MICMIMC30651-6.jpg"
},
{
"id": 2,
"image": "MICMIMC30651-61.jpg",
"url": "http://localhost:8000/images/product/preview/MICMIMC30651-61.jpg"
},
{
"id": 3,
"image": "MICMIMC30651-62.jpg",
"url": "http://localhost:8000/images/product/preview/MICMIMC30651-62.jpg"
},
{
"id": 4,
"image": "MICMIMC30651-63.jpg",
"url": "http://localhost:8000/images/product/preview/MICMIMC30651-63.jpg"
}
]
}
output I wanted :
image : {
"normal_size": [
{
"id": 1,
"image": "MICMIMC30651-6.jpg",
"url": "http://localhost:8000/images/product/preview/MICMIMC30651-6.jpg"
},
{
"id": 2,
"image": "MICMIMC30651-61.jpg",
"url": "http://localhost:8000/images/product/preview/MICMIMC30651-61.jpg"
},
{
"id": 3,
"image": "MICMIMC30651-62.jpg",
"url": "http://localhost:8000/images/product/preview/MICMIMC30651-62.jpg"
},
{
"id": 4,
"image": "MICMIMC30651-63.jpg",
"url": "http://localhost:8000/images/product/preview/MICMIMC30651-63.jpg"
}
]
}
`
Laravel product controller code to pass data to vue component
$normal_size = DB::table('products_images')->where([['products_id', '=', $product]])
->select('products_images.id','products_images.image')
->get()->ToArray();
foreach($normal_size as $value)
{
$value->url = 'http://localhost:8000/images/product/preview/'.$value->image;
}
$output = (array('normal_size' => $normal_size));
return response()->json(($output));
Decode your JSON to convert an array. Format the array structure you want and encode the array to JSON.
$data = '{
"normal_size": [
{
"id": 1,
"image": "MICMIMC30651-6.jpg",
"url": "http://localhost:8000/images/product/preview/MICMIMC30651-6.jpg"
},
{
"id": 2,
"image": "MICMIMC30651-61.jpg",
"url": "http://localhost:8000/images/product/preview/MICMIMC30651-61.jpg"
},
{
"id": 3,
"image": "MICMIMC30651-62.jpg",
"url": "http://localhost:8000/images/product/preview/MICMIMC30651-62.jpg"
},
{
"id": 4,
"image": "MICMIMC30651-63.jpg",
"url": "http://localhost:8000/images/product/preview/MICMIMC30651-63.jpg"
}
]
}';
$output = json_encode(['image' => json_decode($data, true)]);
echo $output;
Working demo.
SOLUTION:
Just adjust the output format before sending.
$output= ['image' => json_decode($data)];
or
$output= array("image" => json_decode($data));
Related
There is json response:
{
"id": "1234567890123456789",
"creation_date": 12345678,
"event": "WAITING_PAYMENT",
"version": "2.0.0",
"data": {
"product": {
"id": 213344,
"name": "Product Name",
"has_co_production": false
},
"affiliates": [
{
"name": "Affiliate name"
}
],
"buyer": {
"email": "buyer#email.com"
},
"producer": {
"name": "Producer Name"
},
"commissions": [
{
"value": 0.65,
"source": "MARKETPLACE"
},
{
"value": 3.10,
"source": "PRODUCER"
}
],
"purchase": {
"approved_date": 1231241434453,
"full_price": {
"value": 134.0
},
"original_offer_price": {
"currency_value": "EUR"
"value": 100.78,
},
"price": {
"value": 150.6
},
"order_date": "123243546",
"status": "STARTED",
"transaction": "HP02316330308193",
"payment": {
"billet_barcode": "03399.33335 33823.303087 198801027 2 876300015000",
"billet_url": "https://billet-link.com/bHP023163303193",
}
},
"subscription": {
"status": "ACTIVE",
"plan": {
"name": "plan name"
},
"subscriber": {
"code": "12133421"
}
}
}
}
My question is how to extract data["buyer"]["email"] in PHP ?
I only need to extract the email information from the buyer table inside the data table.
First, you need to decode the json to a PHP array (or an object), then you can access the requested information from the decoded data.
$data = json_decode('the json string most place here', true);
$email = $data['buyer']['email'];
Place your json string in the first argument of json_decode() function.
I am new to PHP programming and I need your lights!
I have a JSON file like:
"data": [{
"DIAGNOSTIC_TYPE_ID": 1,
"VALUE": "288.0"
},
{
"DIAGNOSTIC_TYPE_ID": 2,
"VALUE": "-0.1"
},
{
"DIAGNOSTIC_TYPE_ID": 3,
"VALUE": "327.67"
},
{
"DIAGNOSTIC_TYPE_ID": 1,
"VALUE": "288.0"
},
{
"DIAGNOSTIC_TYPE_ID": 2,
"VALUE": "-0.1"
},
{
"DIAGNOSTIC_TYPE_ID": 3,
"VALUE": "327.67"
}]
and I have to change it using another json file which is like:
"diagnostics_keys": [
{
"ID": 1,
"type": "BTTPV",
"key": "0_193_bttpv",
"unit": "V"
},
{
"ID": 2,
"type": "BTTPC",
"key": "0_195_bttpc",
"unit": "A"
},
{
"ID": 3,
"type": "AVGKMKWH",
"key": "0_202_avgkmKwh",
"unit": "Km/Kwh"
}]
How can I combine these two (using the ID and type keys/values of the second json and replace the DIAGNOSTIC_TYPE_ID with those on first json)and take a result like the bellow json?
"data": [{
"DIAGNOSTIC_TYPE_ID": BTTPV,
"VALUE": "288.0"
},
{
"DIAGNOSTIC_TYPE_ID": BTTPC,
"VALUE": "-0.1"
},
{
"DIAGNOSTIC_TYPE_ID": AVGKMKWH,
"VALUE": "327.67"
},
{
"DIAGNOSTIC_TYPE_ID": BTTPV,
"VALUE": "288.0"
},
{
"DIAGNOSTIC_TYPE_ID": BTTPC,
"VALUE": "-0.1"
},
{
"DIAGNOSTIC_TYPE_ID": AVGKMKWH,
"VALUE": "327.67"
}]
Would anyone have any points or links that may know and may help?
//change to arrays
$data = json_decode(YOUR_DATA_JSON, true); // I don't know your json variable names, so replace them
$diagnosticKeys = json_decode(YOUR_DIAGNOSTIC_KEYS_JSON, true);
//iterate over data, this is the one you want to change
foreach ($data as &$dataItem) {//(& is for replacing the values)
//another foreach for diagnostic keys
foreach ($diagnosticKeys as $diagnosticKey) {
if ($dataItem["DIAGNOSTIC_TYPE_ID"] == $diagnosticKey["ID"] {
$dataItem["DIAGNOSTIC_TYPE_ID"] = $diagnosticKey["type"];
}
}
}
//change to json again
$data = json_encode($data);
Not tested but should work.
$data1 = json_decode($json1);
$data2 = json_decode($json2);
$result = [];
foreach ($data1->data as $key => $value) {
foreach($data2->diagnostics_keys as $i => $val){
if($value->DIAGNOSTIC_TYPE_ID==$val->ID){
$value->DIAGNOSTIC_TYPE_ID = $val->type;
$result[$key]['DIAGNOSTIC_TYPE_ID'] = $val->type;
$result[$key]['VALUE'] = $value->VALUE;
}
}
}
echo json_encode($result);
I have a list of (the result of a query in DB) like this:
[
{
"id": "1",
"parent_id": null,
"title": "مدادنوکی",
"url": "/medadnoki"
},
{
"id": "2",
"parent_id": null,
"title": "جامعه",
"url": "/commiunity"
},
{
"id": "5",
"parent_id": "1",
"title": "درباره ی مدادنوکی",
"url": "/about"
},
{
"id": "6",
"parent_id": "1",
"title": "درباره ی مدادنوکی",
"url": "/about"
},
{
"id": "7",
"parent_id": "2",
"title": "همکاران",
"url": "/co-worker"
},
{
"id": "8",
"parent_id": "2",
"title": "اساتید",
"url": "/masters"
}
]
But I want to create an object like this:
[
{
"title": "مدادنوکی",
"url": "/medadnoki",
"subs" : [
{
"title": "درباره مدادنوکی",
"url": "/about"
},
{
"title": "درباره مدادنوکی",
"url": "/about"
},
{
"title": "درباره مدادنوکی",
"url": "/about"
},
{
"title": "درباره مدادنوکی",
"url": "/about"
}
]
},
{
"title": "جامعه",
"url": "/soc",
"subs" : [
{
"title": "همکاران",
"url": "/co-work"
},
{
"title": "اساتید",
"url": "/masters"
}
]
}
]
I have handled this process with two foreach in php and it means I process data twice and it is not efficient and will be slow.
Is there any Idea to doing this with just one foreach?
using one foreach means faster than two foreach twice and It will show the result in big data
Assuming you have the results in an order where the parents appear in the results before any children they may have, this should work:
$nested = [];
foreach($results as $r) {
if($r['parent_id'] === null) {
$nested[$r['id']] = [
'title' => $r['title'],
'url' => $r['url'],
'subs' => []
];
continue;
}
$nested[$r['parent_id']]['subs'][] = [
'title' => $r['title'],
'url' => $r['url']
];
}
$nested = array_values($nested);
i am tring to parse a special json content. I got this as an output file from a cucumber execution. The goal is it to decode some values like the name the status and some other content. How can i encode that.
Another concern would be a transformation of json into a CSV.
It is not important for me to use php. Java or Perl would be an alternative.
This file I am gonna call in php with:
$jsonconntent = file_get_contents("/home/xxx/test1.json");
The json conten looks like this (I posted only the beginning):
[
{
"uri": "features/complete_ski.feature",
"id": "complete_ski_with_time",
"keyword": "Feature",
"name": "Complete_Ski_with_time",
"description": "",
"line": 1,
"elements": [
{
"id": "complete_ski_with_time;time_part_preamble",
"keyword": "Scenario",
"name": "time_part_preamble",
"description": "",
"line": 3,
"type": "scenario",
"before": [
{
"output": [
"Default Timestamp start: 1516024716000"
],
"match": {
"location": "features/support/env.rb:32"
},
"result": {
"status": "passed",
"duration": 191690
}
},
{
"match": {
"location": "capybara-2.17.0/lib/capybara/cucumber.rb:13"
},
"result": {
"status": "passed",
"duration": 52117
}
},
{
"match": {
"location": "capybara-2.17.0/lib/capybara/cucumber.rb:21"
},
"result": {
"status": "passed",
"duration": 25885
}
}
],
"steps": [
{
"keyword": "Given ",
"name": "a Android A-Party",
"line": 4,
"output": [
"Got handset with number unvisable, IMSI: notfor, android-Id: yourfone, VNC: 11111, port: 9981"
],
"match": {
"location": "features/step_definitions/idrp_steps.rb:11"
},
"result": {
"status": "passed",
"duration": 1415024760
},
"after": [
{
"match": {
"location": "features/support/env.rb:24"
},
"result": {
"status": "passed",
"duration": 264339
}
}
]
}
Use:
$data = json_decode($jsonconntent, true);
You will have the data with javascript objects as arrays, not PHP objects.
To save it as CSV, it depends on the structure of the data. In this case, it is complicated:
{
"uri": "features/complete_ski.feature",
"id": "complete_ski_with_time",
"keyword": "Feature",
"name": "Complete_Ski_with_time",
"description": "",
"line": 1,
"elements": [
{
"id": "complete_ski_with_time;time_part_preamble",
"keyword": "Scenario",
"name": "time_part_preamble",
"description": "",
"line": 3,
...
How do you put the data in the column elements? Data is so nested that it cannot be transformed into a tabular format with column headers and one value per column in each row.
As to how to access the data, you can do this:
$first_element_id = $data[0]['elements'][0]['id'];
foreach ( $data as $item ) {
$uri = $item['uri'];
foreach ( $item['elements'] as $element ) {
$name = $element['name'];
}
}
As asked in one of the comments, this is how to access the 'Default Timestamp start':
foreach ($data as $item) {
foreach ($item['elements'] as $element) {
foreach ($element['before'] as $before) {
if (isset($before['output'])) {
foreach ($before['output'] as $output) {
echo sprintf("%s\n", $output);
}
}
}
}
}
I am looking for a way to retrieve the number of likes of a Facebook post, based on its post_id. I got hold of a php code from this forum itself..and it's something like
<?php
function fetchUrl($url){
return file_get_contents($url);
}
$json_object = fetchUrl("https://graph.facebook.com/{post_id}/likes?access_token={token}&limit=5000000"); //
$feedarray = json_decode($json_object, true);
$likesNum = count($feedarray['data']); // return the number of items in `data` array
print $likesNum;
?>
But the problem is this method does not retrieve the total likes of a post, since likes are displayed in blocks of 1000, after which theres another link to a different page containing the next set of 1000 likes and so on.
Is there a way to get the total number of likes of a facebook post by a single query?
Add the summary flag ** summary=true**
"https://graph.facebook.com/{post_id}/likes?access_token={token}&summary=true"
{
"data": [
{
"id": "663342380429664",
"name": "Luis Mendoza"
},
{
"id": "1532100840406448",
"name": "Sakazuki Akainu"
},
{
"id": "780666205412913",
"name": "Joaito KoRn"
},
{
"id": "1060933433919925",
"name": "Adrian Sosa"
},
{
"id": "860704407276452",
"name": "Sarah Rosenstrauch"
},
{
"id": "1947974762009431",
"name": "David Prieto"
},
{
"id": "804864302928112",
"name": "Ronal Ortega"
},
{
"id": "1505075359814934",
"name": "Gonzalo Larzen"
},
{
"id": "1431207613804483",
"name": "Victor Clc"
},
{
"id": "508785009283633",
"name": "Rxdry EzDe Cerrx Mcmxii"
},
{
"id": "435355413265946",
"name": "Ángel Fernando Huillca Alonso"
},
{
"id": "163773913961445",
"name": "Pelado Miguel Pin Macias"
},
{
"id": "1479227465674392",
"name": "Releck Solitario"
},
{
"id": "161610054193539",
"name": "MD Sahin MD Sahin"
},
{
"id": "798431050242097",
"name": "Brian Nahuel"
},
{
"id": "624869574305480",
"name": "Saul Alfredo"
},
{
"id": "1642733362665392",
"name": "Junior Zurita"
},
{
"id": "134907406871404",
"name": "Wil Peña"
},
{
"id": "10153052770952668",
"name": "Miguel Peña Cáceres"
},
{
"id": "1461494580846182",
"name": "Darian Suarez"
},
{
"id": "365762500250317",
"name": "Igarashi Ganta"
},
{
"id": "750032685093387",
"name": "Camila Barbé"
},
{
"id": "781013541941152",
"name": "Gonzalo Nievas"
},
{
"id": "756520927743339",
"name": "Jonathan C. Duran Cuellar"
},
{
"id": "1504488093199860",
"name": "Maxi Russo"
}
],
"paging": {
"cursors": {
"before": "NjYzMzQyMzgwNDI5NjY0",
"after": "MTUwNDQ4ODA5MzE5OTg2MAZDZD"
},
"next": "https://graph.facebook.com/v2.3/1009501939072385/likes?access_token=TOKEN..."
},
"summary": {
"total_count": 4303
}
}