I have 2 different jsons and I need to get one inside the other.
JSON 1
[{
"id":"1",
"texto":"Vamos newells 17471934",
"fecha":"2019-06-24 12:09:12",
"categoria":"1",
"idpayment":"Reference_1561388952",
"provincia":"1",
"estado":"NO",
"email":"newells#gmail.com"
}]
JSON 2
{
"Texto": " VENDO O PERMUTO",
"imageJob": {
"pathConvertido": "ClasificadosPNG/0011311247.png",
"convertido": true,
"id": 5011
},
"rubroClasificado": {
"CodigoRubro": 150,
"id": 76
}
}
I need the second one inside the first one for use with javascript
I tried the array_merge() php function without getting results
since JSON1 is an array of JSON-object and JSON2 is just a JSON-object.
in addition to that you said, 'I need the second one inside the first one for use with javascript'. therefore, you can test this code https://3v4l.org/1HGNF/perf#output
please compare all performances in mem-usage and timing
$j1 = '[{
"id":"1",
"texto":"Vamos newells 17471934",
"fecha":"2019-06-24 12:09:12",
"categoria":"1",
"idpayment":"Reference_1561388952",
"provincia":"1",
"estado":"NO",
"email":"newells#gmail.com"
}]';
$j2 = '{
"Texto": " VENDO O PERMUTO",
"imageJob": {
"pathConvertido": "ClasificadosPNG/0011311247.png",
"convertido": true,
"id": 5011
},
"rubroClasificado": {
"CodigoRubro": 150,
"id": 76
}
}';
$j1 = json_decode($j1, true);
$j2 = json_decode($j2, true);
$j1[] = $j2;
var_dump(json_encode($j1));
You can use json_decode with parameter true to convert JSON into an array , then use array_merge to make them a single array
$j1 = '[{"id":"1","texto":"Vamos newells 17471934","fecha":"2019-06-24 12:09:12","categoria":"1","idpayment":"Reference_1561388952","provincia":"1","estado":"NO","email":"newells#gmail.com"}]';
$j1arr = json_decode($j1, true);
$j2 = ' {
"Texto": " VENDO O PERMUTO",
"imageJob": {
"pathConvertido": "ClasificadosPNG/0011311247.png",
"convertido": true,
"id": 5011
},
"rubroClasificado": {
"CodigoRubro": 150,
"id": 76
}
}';
$j2arr = json_decode($j2, true);
$r = array_merge($j1arr[0], $j2arr);
You can use the merged array in javascript by using json_encode
json_encode($r)
https://3v4l.org/WKX1U
Do it simply like this way without any extra array merging methods-
<?php
$json1 = json_decode('[{"id":"1","texto":"Vamos newells 17471934","fecha":"2019-06-24 12:09:12","categoria":"1","idpayment":"Reference_1561388952","provincia":"1","estado":"NO","email":"newells#gmail.com"}]',1);
$json2 = json_decode('{"Texto":" VENDO O PERMUTO","imageJob":{"pathConvertido":"ClasificadosPNG/0011311247.png","convertido":true,"id":5011},"rubroClasificado":{"CodigoRubro":150,"id":76}}',1);
$json1[] = $json2; // add second json to first json
print_r($json1);
echo json_encode($json1);
?>
WORKING DEMO: https://3v4l.org/qhsJq
As you said you want to process the resulting data in JavaScript, and as per your question you want second json inside the first json. You can do something like this.
You will get a json as final result.
$first = '[{
"id":"1",
"texto":"Vamos newells 17471934",
"fecha":"2019-06-24 12:09:12",
"categoria":"1",
"idpayment":"Reference_1561388952",
"provincia":"1",
"estado":"NO",
"email":"newells#gmail.com"
}]';
$first = str_replace(['[',']','}'], '', $first);
$second = '{
"Texto": " VENDO O PERMUTO",
"imageJob": {
"pathConvertido": "ClasificadosPNG/0011311247.png",
"convertido": true,
"id": 5011
},
"rubroClasificado": {
"CodigoRubro": 150,
"id": 76
}
}';
$second = preg_replace('/\{/', ',', $second,1);
print_r($first.$second);
As result you will get a valid json, second json inside your first json, you can validate here
Related
This is my JSON result:
{
"#odata.context": "http://wabi-west-europe-redirect.analysis.windows.net/v1.0/collections/washington/workspaces/37380bc1-dd47-4c95-8dbd-5efecafc8b26/$metadata#reports",
"value": [
{
"id": "6ea77895-f92a-4ca6-90f7-cdade3683cd6",
"modelId": 0,
"name": "america",
"webUrl": "https://app.powerbi.com/reports/6ea77895-f92a-4ca6-90f7-cdade3683cd6",
"embedUrl": "https://embedded.powerbi.com/appTokenReportEmbed?reportId=6ea77895-f92a-4ca6-90f7-cdade3683cd6",
"isOwnedByMe": true,
"isOriginalPbixReport": false,
"datasetId": "3f1f480c-4a8c-4756-87eb-fc29f5d76de3"
},
{
"id": "ce558be6-aaf9-4bee-b344-6db7754e572b",
"modelId": 0,
"name": "dency",
"webUrl": "https://app.powerbi.com/reports/ce558be6-aaf9-4bee-b344-6db7754e572b",
"embedUrl": "https://embedded.powerbi.com/appTokenReportEmbed?reportId=ce558be6-aaf9-4bee-b344-6db7754e572b",
"isOwnedByMe": true,
"isOriginalPbixReport": false,
"datasetId": "5264cf84-214a-4c33-8f8e-f421d8ce1846"
}
]
}
In PHP im getting into
$response = json_decode($aboveresult);
But My problem is the value is in array.I want to get both the array value like id,modelId,Name,...
Please help me.
I tried $response['value'].But its showing error like Cannot use object of type stdClass as array
json_decode() accepts a second parameter, which is by default false. If you pass true, the function will return you an associative array instead of an instance of stdClass and you can work with it the way you tried before.
You have to change:
$response = json_decode($aboveresult,true);
When you mentioned the second parameter as true you will get the ASSOCIATIVE array
Try this
echo "<pre>";
$json_data = json_decode($json); //$json = your json string
print_r($json_data->value);
foreach($json_data->value as $value) {
echo 'ID: '.$value->id .'<br>';
echo 'modelId: '.$value->modelId .'<br>';
echo 'name: '.$value->name .'<br>';
}
I try to read IME field in PHP from following JSON FORMAT:
{"komentarji": [ {"RC_KOMENTARJI": [ {
"K_ID": 101,
"STATUS": "A",
"IME": "boris",
"E_MAIL": "test#example.com",
"KOMENTAR": "testni vnos",
"IP": "10.0.0.6",
"DATUM_ZAPISA": "2016-12-03T23:23:47Z",
"DATUM_UREJANJA": "2016-12-03T23:24:01Z"
},
{
"K_ID": 1,
"STATUS": "A",
"IME": "Peter",
"KOMENTAR": "Zelo profesionalno ste opravili svoje delo.",
"IP": "10.0.0.8",
"DATUM_ZAPISA": "2011-05-04T00:00:00Z"
}
] } ] }
How can I reach that field via foreach in PHP? Thank you.
Let you decode the json to object named $result.
If you want to read first IME then try this
$result->komentarji[0]->RC_KOMENTARJI[0]->IME
If you want to read all IME then you have to apply loop throw komentarji and RC_KOMENTARJI
Decode it by using json_decode().
$object = json_decode($json);
// result in object
$array = json_decode($json, true);
// result in array
You can try this:
$array = json_decode($json, true);
foreach ($array['komentarji'] as $key => $value) {
foreach ($value['RC_KOMENTARJI'] as $k => $val) {
echo $val['IME'] . "<br/>";
}
}
This will print:
boris
Peter
Hope it helps!!!
I need to parse this JSON using PHP
[{
"options": {
"allowUTurn": false
},
"latLng": {
"lat": 44.91138,
"lng": 7.671783
},
"name": "Corso Vinovo, Carignano, TO, Piemont, Italy",
"_initHooksCalled": true
}, {
"options": {
"allowUTurn": false
},
"latLng": {
"lat": 44.909979,
"lng": 7.676234
},
"name": "Il Tempio del Pane, Corso Cesare Battisti, Carignano, TO, Piemont, Italy",
"_initHooksCalled": true
}, {
"options": {
"allowUTurn": false
},
"latLng": {
"lat": 44.907805,
"lng": 7.674952
},
"name": "Banca Intesa, Via Ferdinando Salotto, Carignano, TO, Piemont, Italy",
"_initHooksCalled": true
}]
to extract the coordinates in lat / lon.
What have I to use after
echo $wayPoints->?????
and how I create a for cicle to extract all the coordinates?
Any help will be appreciated!!Thank you!
Cesare
EDIT: a code sample (note that the JSON come from a POST parameter ...)
<?php
echo "Waypoints ...</br>";
echo "</br>";
echo $_POST['wayPoints'];
$wayPoints = $_POST['wayPoints'];
$json = json_decode($wayPoints);
foreach($json as $f){
echo $f['latLng']['lat'];
echo $f['latLng']['lng'];
}
?>
so should be more clear ... (the code NOT working ...)
Thank you again ...
EDIT 2: this code work !!!
<?php
echo "Waypoints ...</br>";
echo "</br>";
echo $_POST['wayPoints'];
$wayPoints = $_POST['wayPoints'];
$json = json_decode($wayPoints, true);
foreach($json as $f){
echo "</br>";
echo $f['latLng']['lat'];
echo "</br>";
echo $f['latLng']['lng'];
echo "</br>"; }
?>
the output is
44.91138
7.671783
44.909979
7.676234
44.907805
7.674952
Thank you all!
This will convert your json object into an associative array, then iterate with foreach.
//use json_decode in associative mode
$decoded = json_decode($json, true);
//Your object is now an array called $decoded
//Your locations are subarrays of $decoded
//The co-ords are subarrays of each $locationArray
foreach($decoded as $locationArray)
{
echo "The co-ordinates for {$locationArray['name']} are: {$locationArray['latLng']['lat']},{$locationArray['latLng']['lng']}" . PHP_EOL;
}
First you need to do $file = json_decode()
and then the file you get just add to foreach:
foreach($file as $f){
echo $f['latLng']['lat'];
echo $f['latLng']['lng'];
}
I'm retrieving bibliographic data via an API (zotero.org), and it is similar to the sample at the bottom (just way more convoluted - sample is typed).
I want to retrieve one or more records and display certain values on the page. For example, I would like to loop through each top level record and print the data in a nicely formated citation. Ignoring the proper bib styles for the moment, let's say I want to just print out the following for each record returned:
author1 name, author2 name, article title, publication title, key
This doesn't match the code, because I've clearly been referencing the key value pairs incorrectly and will just make a mess of it.
The following is laid out like the data if I request JSON format, though I can request XML data instead. I'm not picky; I've tried using each with no luck.
[
{
"key": "123456",
"state": 100,
"data": {
"articleTitle": "Wombat coprogenetics: enumerating a common wombat population by microsatellite analysis of faecal DNA",
"authors": [
{
"firstName": "Sam C.",
"lastName": "Smith"
},
{
"firstName": "Maxine P.",
"lastName": "Jones"
}
],
"pubTitle": "Australian Journal of Zoology",
"tags": [
{
"tag": "scary"
},
{
"tag": "secret rulers of the world"
}
]
}
},
{
"key": "001122",
"state": 100,
"data": {
"articleTitle": "WOMBAT and WOMBAT-PK: Bioactivity Databases for Lead and Drug Discovery",
"authors": [
{
"firstName": "Marius",
"lastName": "Damstra"
}
],
"pubTitle": "Chemical Biology: From Small Molecules to Systems Biology",
"tags": [
{
"tag": "Wrong Wombat"
}
]
}
}
]
If there is a mistake in brackets, commas, etc. it is just a typo in my example and not the cause of my issue.
decode your json as array and iterate it as any array as flowing:
$json_decoded= json_decode($json,true);
$tab="\t";
foreach ($json_decoded as $key => $val) {
echo "Article ".$val["key"]."\n" ;
echo $tab."Authors :\n";
foreach ($val["data"]["authors"] as $key => $author){
echo $tab.$tab. ($key+1) ." - ".$author["firstName"]. " ".$author["lastName"]."\n";
}
echo $tab."Article Title: ".$val["data"]["articleTitle"] ."\n";
echo $tab."Publication Title: ".$val["data"]["pubTitle"] ."\n";
echo $tab."Key: ".$val["key"]."\n";
}
run on codepad
and you can use the same method for xml as flowing:
$xml = simplexml_load_string($xmlstring);
$json = json_encode($xml);
$json_decoded = json_decode($json,TRUE);
//the rest is same
for xml you can use the SimpleXml's functions
or DOMDocument class
Tip
to know the structure of your data that api return to you after it converted to array use var_dump($your_decoded_json) in debuging
Something like this might be a good start for you:
$output = [];
// Loop through each entry
foreach ($data as $row) {
// Get the "data" block
$entry = $row['data'];
// Start your temporary array
$each = [
'article title' => $entry['articleTitle'],
'publication title' => $entry['pubTitle'],
'key' => $row['key']
];
// Get each author's name
foreach ($entry['authors'] as $i => $author) {
$each['author' . ++$i . ' name'] = $author['firstName'] . ' ' . $author['lastName'];
}
// Append it to your output array
$output[] = $each;
}
print_r($output);
Example: https://eval.in/369313
Have you tried to use array_map ?
That would be something like:
$entries = json_decode($json, true);
print_r(array_map(function ($entry) {
return implode(', ', array_map(function ($author) {
return $author['firstName'];
}, $entry['data']['authors'])) . ', ' . $entry['data']['articleTitle'] . ', ' . $entry['key'];
}, $entries));
I'm having a bit of trouble here...
I'm trying to grab some values from a json file here, and it can be formatted here.
The json file looks like this:
{
"type": "success",
"message": "OK",
"data": {
"mainWeaponStats": [
{
"category": "Machine guns",
"timeEquipped": 3507,
"startedWith": null,
"code": "mgRPK",
"headshots": 18,
"name": "RPK",
"kills": 100,
"deaths": null,
},
{
"category": "Handheld weapons",
"timeEquipped": 5452,
"startedWith": null,
"code": "wahUGL",
"headshots": 1,
"name": "Underslung Launcher",
"kills": 108,
"deaths": null,
},
{
"category": "Sniper rifles",
"timeEquipped": 307,
"startedWith": null,
"code": "srMK11",
"headshots": 0,
"name": "MK11",
"kills": 2,
"deaths": null,
},
And so on.
I want to grab the kills of one of these items. Meaning I want to give a parameter like "Underslung Launcher" and return with 108.
In this case, the "Underslung Launcher".
I'm looking for a code like this:
$gamemode = $decode['data']['topStats']['mapMode'];
But if anyone know a better way, please, tell me.
Since the items in the list doesn't have a "name", unlike "data" & "mainWeaponStats", I can't really figure out how to do this.
Edit:
This is the relevant code so far:
$weaponstats = "http://battlelog.battlefield.com/bf3/weaponsPopulateStats/" . $bf3id . "/1/";
$content = file_get_contents($weaponstats);
$decode = json_decode($content, true);
$mainweaponstats = $decode['data']['mainWeaponStats'];
As you can see, I'm having a hard time learning Json.
I'm trying to read up on it, but as of now, I can't figure this out.
I don't really know how I'm going to do it, as the values I'm trying to find are within the same group.
$mainweaponstats = $decode['data']['mainWeaponStats'];
This is an array of objects (well arrays because you passed ,true to json_decode). Just loop through this and find what you want.
$search = 'Underslung Launcher';
$kills = 0;
foreach($mainweaponstats as $w){
if($w['name'] === $search){
$kills = $w['kills'];
break;
}
}
echo $kills;
<?
$name = "Underslung Launcher";
$json = file_get_contents("json.php");
$dec = array();
$dec = json_decode($json,true);
$datas = $dec['data']['mainWeaponStats'];
foreach($datas as $data)
{
if($data['name']==$name) {
echo $data['kills'];
break;
}
}
?>