PHP - save object key from json - php

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..

Related

PHP How to properly merge arrays for following json structure

So i tried a lot of possible codes out but i can't seem to find a proper solution.
First let's start with the the wished array (i will show it in a json format as it's easier to read)
{
"transaction": {
"input": [
{
"address": "a",
"value": 4294967295
},
{
"address": "b",
"value": 51515
}
],
"output": [
{
"address": "aa",
"value": 551
},
{
"address": "bb",
"value": 66564
}
]
}
}
I'm using 2 foreach loops to get data that i wanna put in inputs & outputs
Here's the code im using:
//Get Output Addresses & Value
$tmp_array = array();
foreach($json['result']['vout'] as $a)
{
$value = $a['value'];
$address = $a['scriptPubKey']['addresses'][0];
$tmp_array = array('wallet' => $address, 'value' => $value);
$input = array_merge($input, $tmp_array);
};
$input = array('inputs' => $tmp_array);
$input = json_encode($input);
print_r($input);
That's the code for me getting the data and trying to put it into the array. Now i have a problem, it only adds data from the last iteration of the loop. I'm trying to get a code that gets it in a strucuture like above. Whatever solution gets sent, it should be applicable so i can paste the same code in the other loop that is for the outputs
You are assigning the $input variable after the loop with the value of $tmp_array which will be the value from the last iteration, as you described. To fix this you should initialize the $input array as empty array at the beginning and merge that with the new data:
//Get Output Addresses & Value
$inputs = array();
foreach($json['result']['vout'] as $a)
{
$value = $a['value'];
$address = $a['scriptPubKey']['addresses'][0];
$tmp_array = array('wallet' => $address, 'value' => $value);
$inputs[] = $tmp_array; // push to array
};
$input = json_encode(array('inputs' => $inputs));
print_r($input);

php - Reach empty JSON array [duplicate]

This question already has answers here:
How to loop through PHP object with dynamic keys [duplicate]
(16 answers)
Closed 6 years ago.
I use Microsoft Face API and I want to show data to final user, but how can I use foreach to atteint faceAttributes->age ?
There is an example of JSON file
[
{
"faceId": "c5c24a82-6845-4031-9d5d-978df9175426",
"faceRectangle": {
"width": 78,
"height": 78,
"left": 394,
"top": 54
},
"faceAttributes": {
"age": 71.0,
"gender": "male",
"smile": 0.88,
"facialHair": {
"mustache": 0.8,
"beard": 0.1,
"sideburns": 0.02
}
},
"glasses": "sunglasses",
"headPose": {
"roll": 2.1,
"yaw": 3,
"pitch": 0
}
}
}
]
I tried this code but not working :
<?php
$json = file_get_contents('file.json');
$data = json_decode($json);
if (count($data->faceAttributes)) {
// Cycle through the array
foreach ($data->faceAttributes as $idx => $faceAttributes) {
// Output a row
echo $faceAttributes->age ;
echo $faceAttributes->gender ;
?>
Thanks !
You don't have to iterate the object using foreach as the 'age' is a property of $data->faceAttributes itself.
Use this instead
if (count($data->faceAttributes)) {
echo $data->faceAttributes->age;
echo $data->faceAttributes->gender;
}
However, $data is an array and which $data you are using is actually $data[0]
So, if there is only one element in data array you can do
$data = $data[0] or $data = json_decode($json)[0]
Or, you can iterate through $data in case of more then one element.

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

PHP json string: getting an associative array object

I have a json file with data like this (this is a partial view of the file to show structure):
{
"state": {
"ALABAMA": {
"ZOLD": [ "101", "102" ],
"ZNEW": [ "11", "12" ]
},
"ALASKA": {
"ZOLD": [ "5001", "5002", "5003", "5004", "5005", "5006", "5007", "5008", "5009", "5010"],
"ZNEW": [ "21", "22", "23", "24", "25", "26", "27", "28", "29", "20"]
}
}
}
What I want to do is search through it to find a value in the ZOLD field = $OLD, then return the value of the corresponding ZNEW array. I've tried going in with foreach and can get the arrays to echo out, but I'm not sure of what the value will be. Here's the code I have:
function translateZone($OLD)
{
$OLD = "5010"; //for testing purposes a constant but will be variable
$zStr = file_get_contents('getnew.json');
$zJson = json_decode($zStr,true);
foreach($zJson as $key=> $jsons)
{
foreach($jsons as $key=>$values)
{
foreach($values as $key=>$vals)
{
$counter=0;
foreach($vals as $key=>$vls)
{
$counter ++;
echo var_dump($vls);//I can see the values,but now what?
if ($vls == $OLD)
{
$zTemp = Help here -some array value of counter??
}
}
}
return $zTemp;
}
}
I've searched through a bunch of other questions but haven't found something close enough to help with the problem.
Additional information: I may or may not know the "state" string (i.e. "Alaska") but I may want to return this information as well based on the found value.
Thanks for the help.
Instead of trying to loop through ZOLD, you could use array_search (assuming that the $OLD value can only appear once in the data). This function will either return a number for the index of the value you search for or false if it cannot find it:
$index = array_search($OLD,$values['ZOLD']);
if ($index !== FALSE) {
$zTemp = $values['ZNEW'][$index];
}
This would replace your two innermost for loop (as you need the other loops to get down to this level) and iterate through each state. At this point as well, $key would be defined to your state name.
Here is another way to complete your task, this one with array_map function:
$jsonArray = json_decode($your_file_content, true);
$oldVal = "5005";
$result = [];
foreach( $jsonArray["state"] as $k => $v ) {
/**
* Here we're building an array or pairs ZOLD => ZNEW values
*/
$pairs = array_map(function($o, $n) {
return [ $o => $n ];
}, $v["ZOLD"], $v["ZNEW"]);
/**
* Filling up the result
*/
foreach( $pairs as $p )
if( isset($p[$oldVal]) )
$result[] = [
"state" => $k,
"ZNEW" => $p[$oldVal]
];
}
var_dump($result);
$result dump will contains a list or assoc arrays with "state" and "ZNEW" keys, if the corresponding ZNEW values will be found

Grabbing unnamed(?) data from json with 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;
}
}
?>

Categories