Grabbing unnamed(?) data from json with PHP - php

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

Related

Merge two JSONs php

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

Reach licensedContent value on Youtube Api - PHP

In an effort to get consistent music search returns on Youtube API, I resorted to separate licensed content to non-licensed one.
The Json from the call is this:
{
"kind": "youtube#videoListResponse",
"etag": "\"XI7nbFXulYBIpL0ayR_gDh3eu1k/Y0E2MZ3qwZc8Z7rZDINIYA1uY0I\"",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 1
},
"items": [
{
"kind": "youtube#video",
"etag": "\"XI7nbFXulYBIpL0ayR_gDh3eu1k/Xup77LEmvulitH-oe1DkTBPumV4\"",
"id": "plIZho8Nd2g",
"contentDetails": {
"duration": "PT4M34S",
"dimension": "2d",
"definition": "hd",
"caption": "true",
"licensedContent": false,
"projection": "rectangular"
}
}
]
}
But I can't seem to reach the value in the PHP foreach loop. Is anything wrong with my code?
<?php
$api = "MY API KEY";
$link2 = "https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=plIZho8Nd2g&key=" . $api;
$video2 = file_get_contents($link2);
$video2 = json_decode($video2, true);
foreach ($video['items'] as $data) {
foreach ($data['contentDetails'] as $data2) {
$licensed = $data2['licensedContent'];
echo $licensed . "<br>";
}
}
?>
You should be getting some warnings which would help you solve this. There are a few little issues:
Typo: foreach ($video['items'] as $data) { - $video should be $video2
contentDetails is an object, not an array. So by doing a foreach loop on it you're looping through each property name individually. Therefore none of the properties will contain licensedContent. One of them will be licensedContent, but since we know we want that one, we can just access it directly.
Since licensedContent (and by extension $licensed) is a boolean, and is set to false, echo will not actually output anything visible - this is a quirk of the echo command in PHP. We can fix it by checking the value and then echoing an appropriate string.
Put all that together and this is what you get:
foreach ($video2['items'] as $data) {
$licensed = $data['contentDetails']['licensedContent'];
echo ($licensed == false ? "false" : "true")."<br/>";
}
Live demo here: http://sandbox.onlinephpfunctions.com/code/7ca09960ec3e86ccb4bd49038ad851c3c93ef5de

Json to php condition text part

I only want to display the text from the condition part, see the JSON below
"forecast": {
"forecastday": [
{
"date": "2017-12-01",
"date_epoch": 1512086400,
"day": {
"maxtemp_c": 4.9,
"maxtemp_f": 40.8,
"mintemp_c": 0.9,
"mintemp_f": 33.6,
"avgtemp_c": 1.8,
"avgtemp_f": 35.2,
"maxwind_mph": 9.8,
"maxwind_kph": 15.8,
"totalprecip_mm": 0,
"totalprecip_in": 0,
"avgvis_km": 18,
"avgvis_miles": 11,
"avghumidity": 88,
"condition": {
"text": "Partly cloudy",
"icon": "//cdn.apixu.com/weather/64x64/day/116.png",
"code": 1003
},
"uv": 0.5
},
My code shows all the parts from condition, i only want the text part.
See my code below:
$json = json_decode($json, true);
foreach ($json['forecast']['forecastday'] as $forecast) {
echo 'date: '.$forecast['date'].'<br />';
foreach ($forecast['day']['condition'] as $condition) {
echo ''.$condition.'<br />';
}
}
$json = json_decode($json, true);
$counter=0;
foreach ($json['forecast']['forecastday'] as $forecast) {
{ if ($counter++ == 0) continue; }
echo 'date: '.$forecast['date'].'<br />';
echo 'date: '.$forecast['day']['condition']['text'].'<br />';
}
So a bit more explanation about how a multidimensional array works.
Each nested array should be treated-accessed/parsed as a new array. So in your example you have the main array $json , this is where magic starts.
After that in order to reach the text you need to map your array to find the route that will get you there. If you go for
print_r($json)
you will see that you get your whole array. Now you can see that you have to access forecast array first and so you do it like $json['forecast'] and you are inside the nested array. Same logic leads you to day field.
New Edit: This will output your second record only.

PHP - save object key from json

Sorry for the noobie question, I am trying to save some json data on to my database. The problem is, i don't know how to get any of the "parent_names". The "parent_name" is always the same as the child "name".
price-data.json
[
{
"Flag": {
"name": "Flag",
"safe_price": "118.31",
"safe_net_price": "110.60",
"total_volume": 3148,
"7_days": {
"median_price": "118.31",
"lowest_price": "100.00",
"highest_price": "132.25",
"volume": 94
}
},
"Pole": {
"name": "Pole",
"safe_price": "81.21",
"safe_net_price": "70.62",
"total_volume": 1,
"7_days": {
"volume": 0
}
},
"Net": {
"name": "Net",
"safe_price": "0.89",
"safe_net_price": "0.84",
"total_volume": 763,
"7_days": {
"median_price": "0.89",
"lowest_price": "0.65",
"highest_price": "1.08",
"volume": 30
}
}
}
]
php
$filename = "price-data.json";
$data = file_get_contents($filename);
$array = json_decode($data, true);
foreach($array as $row)
{
$sql = "INSERT INTO table_all_prices(parent_name, name, safe_price, safe_net_price, total_volume, median_price, lowest_price, highest_price, volume) VALUES (
'".$row["parent_name"]."',
'".$row["parent_name"]["name"]."',
'".$row["parent_name"]["safe_price"]."',
'".$row["parent_name"]["safe_net_price"]."',
'".$row["parent_name"]["total_volume"]."',
'".$row["parent_name"]["7_days"]["median_price"]."',
'".$row["parent_name"]["7_days"]["lowest_price"]."',
'".$row["parent_name"]["7_days"]["highest_price"]."',
'".$row["parent_name"]["7_days"]["volume"]."'
)";
}
echo "All Prices inserted to database";
You need to access the key from the current array level in the loop, you can do that by
foreach($array as $parent_name => $row)
Adding a variable in before the $row variable think of this like array access
array( 'key' => 'value' )
Same deal. Now because you are in the "parent_name" level of the array you don't need to put the additional access key in there. So for this
$row["parent_name"]["7_days"]["volume"]
You can just do
$row["7_days"]["volume"]
Because you will be working in this part of the json
"name": "Net",
"safe_price": "0.89",
"safe_net_price": "0.84",
"total_volume": 763,
"7_days": {
"median_price": "0.89",
"lowest_price": "0.65",
"highest_price": "1.08",
"volume": 30
}
Then because you have an outer array wrapper on your json [{ .. }] those square brackets. you may need to do $array[0] or $array = reset($array). Reset is probably better ( if that turns out to be the case ) because you will avoid some warning messages from PHP if the array is empty. Essentially, trying to access a key of 0 will give you an undefined index warning if it's empty..

How to loop over and access various elements in an array that is both multidimentional and associative? PHP, either JSON or XML

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

Categories