How to get a thing from a Json text? - php

i want to know how can i extract a word from a json encoded or decoded.
Example:
From:
{"51973658":{"id":51973658,"name":"Covrigel","profileIconId":748,"summonerLevel":30,"revisionDate":1419865098000}}
I want to see just "Covrigel".
Is that possible?

This is a simple array. You can access that by something like this,
echo $array_name['51973658']['name'];
EDIT after question change:
$json = json_decode($json_array, true);
echo $json['51973658']['name'];

All you have to do is convert it to a PHP array.
$json = '{"51973658":{"id":51973658,"name":"Covrigel","profileIconId":748,"summonerLevel":30,"revisionDate":1419865098000}}';
$json = json_decode($json, $array = true);
echo $json['51973658']['name'];

Decode the JSON as an associative array then echo the value you need.
<?php
$json = '{"51973658":{"id":51973658,"name":"Covrigel","profileIconId":748,"summonerLevel":30,"revisionDate":1419865098000}}';
$data = json_decode($json, true);
echo $data['51973658']['name'];
?>

Related

How to read specific data from an object?

{"TransactionInfo":{"Date":"06\/04\/2018","Time":"09:29 ET","TransactionCharge":{"MonetaryValue":"0.00","CurrencyCode":{}}},"ShipmentEstimate":{"CurrencyCode":"EUR","ShipmentCharges":{"TaxesAndFees":"1.7532","AdditionalInsuranceCost":"0.00","TransportationCost":"0.00","SubTotal":"1.7532"},"ProductsCharges":{"Product":{"TariffCode":"5109.90.80.00","Charges":{"Duties":"75.0021","TaxesAndFees":"0.00","VAT":"0.00","CostOfGoods":"1250.00","SubTotal":"1325.0021"}},"ProductsSubTotal":"1325.0021"},"TotalLandedCost":"1326.7553"},"SuppressQuestionIndicator":"Y"}
How can I get only the value of TariffCode?
Result must be: 5109.90.80.00
<?php
$json = '{"TransactionInfo":{"Date":"06\/04\/2018","Time":"09:29 ET","TransactionCharge":{"MonetaryValue":"0.00","CurrencyCode":{}}},"ShipmentEstimate":{"CurrencyCode":"EUR","ShipmentCharges":{"TaxesAndFees":"1.7532","AdditionalInsuranceCost":"0.00","TransportationCost":"0.00","SubTotal":"1.7532"},"ProductsCharges":{"Product":{"TariffCode":"5109.90.80.00","Charges":{"Duties":"75.0021","TaxesAndFees":"0.00","VAT":"0.00","CostOfGoods":"1250.00","SubTotal":"1325.0021"}},"ProductsSubTotal":"1325.0021"},"TotalLandedCost":"1326.7553"},"SuppressQuestionIndicator":"Y"}';
$array = json_decode($json, true);
echo $array['ShipmentEstimate']['ProductsCharges']['Product']['TariffCode'];
See it in action here: https://3v4l.org/2WBs6

Decode php://input json

I have this text from file_get_contents('php://input'):
[{"email":"text#examlple.com","event":"processed","sg_event_id":"JJTr9qA","sg_message_id":"AjvX5L7IQeGOfxmJV-OCnw","smtp-id":"<AfxmJV-OCnw#ismon1.sendgrid.net>","timestamp":16813363}]
I need to get single element like email or event, but haven't been able to get json_decode and others to work.
$obj = json_decode(file_get_contents('php://input'));
How can I reference a single element in the json data?
You have an array, so, you need to get the first element:
$json = '[{"email":"text#examlple.com","event":"processed","sg_event_id":"JJTr9qA","sg_message_id":"AjvX5L7IQeGOfxmJV-OCnw","smtp-id":"<AfxmJV-OCnw#ismon1.sendgrid.net>","timestamp":16813363}]';
$obj = json_decode($json);
echo $obj[0]->email; //output text#examlple.com
Here you go, here's a fully working answer:
<?php
$str = '[{"email":"text#examlple.com","event":"processed","sg_event_id":"JJTr9qA","sg_message_id":"AjvX5L7IQeGOfxmJV-OCnw","smtp-id":"<AfxmJV-OCnw#ismon1.sendgrid.net>","timestamp":16813363}]';
$obj = json_decode($str);
echo $obj[0]->email;

How do I get variable values from this JSON array?

So I have a URL that returns the following:
[{"_id":{"champ2_id":63,"champ1_id":2,"role":"TOP"},"count":4,"champ1":{"thirtyToEnd":0,"goldEarned":10727.5,"zeroToTen":0,"minionsKilled":158,"winrate":0,"assists":6.25,"role":"TOP","deaths":6,"kills":4,"wins":0,"totalDamageDealtToChampions":17350.75,"twentyToThirty":0,"tenToTwenty":0,"neutralMinionsKilledTeamJungle":1.75,"killingSprees":0.75,"weighedScore":27214.5375},"champ2":{"twentyToThirty":0,"wins":4,"winrate":1,"kills":5.75,"neutralMinionsKilledTeamJungle":5,"totalDamageDealtToChampions":21881.25,"role":"TOP","assists":7,"tenToTwenty":0,"thirtyToEnd":0,"zeroToTen":0,"goldEarned":12371.75,"killingSprees":1.25,"minionsKilled":140.5,"deaths":4.25,"weighedScore":33166.587499999994}]
I have learned how to get the value of a key in an array when the URL returns something simpler. For example if the URL returns:
{"id":34743514,"accountId":49161997,"name":"League of Fiddle","profileIconId":786,"revisionDate":1514093712000,"summonerLevel":52}
I can echo the id with this code:
$json = file_get_contents(URL);
$data = json_decode($json, true);
echo $data['id'];
That's easy. But when I try to use the same code for the more complicated stuff, like say I want to get the value of _id champ2_id, I've tried:
$json = file_get_contents(URL);
$data = json_decode($json, true);
echo $data['_id']['champ2_id'];
But this says _id is an undefined index. What am I doing wrong?
should be
$data[0]['_id']['champ2_id'];

Json strings decode mysql

I am fetching the "form_json" from database which has json saved for all form templates. The code for that is:
<?php
include ('connection.php');
$id = intval($_GET['frmid']);
$results = mysqli_query($conn, "SELECT form_json FROM form WHERE form_id=$id");
while ($row = mysqli_fetch_array($results))
{
$url = $row['form_json'];
echo $url; //Outputs: 2
}
?>
Now, I want to decode all these jsons which are being saved in row form_json. Is there anyway to traverse or something?
$json ='{"value":"Form Title","name":"title"}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
This is how we decode but this is for one string / one form template. I can have many json strings / many form templates saved in database. I should be able to decode all.
The best thing you can do for that is, to store the single json strings into an array. Problem is, that your json strings are encoded, so you need to concat them first if you want all results at once:
$json = array();
$results = mysqli_query($conn, "SELECT form_json FROM form WHERE form_id=$id");
while ($row = mysqli_fetch_array($results)) {
array_push($json, $row['form_json']);
}
$json = implode(",",$json); // concats all json strings with commas
At this point, you have one large string. To make a successful decode, you have to wrap a container around the string to be a valid parse since your values are already json and you need a container for them:
$json = '{"templates": [' . $json . ']}';
Now you have a valid json string that can be decoded, either as array or object. For better understanding a simple working example:
<?php
$json1 = '{"value":"Form Title","name":"title"}';
$json2 = '{"value":"A Message","name":"message"}';
$arr = array($json1, $json2);
$json = implode(",", $arr);
$json = '{"templates": ['.$json.']}';
$json = json_decode($json, true); // true if you want an array, false if you want an object
echo "<pre>";
print_r($json); // returns a multidimensional array of all templates
echo "</pre>";
?>
$json = '{"value":"Form Title","name":"title"}';
$data = json_decode($json);
$value = $data->value; //will output = Form Title
$title = $data->title; //will output = title
i hope this help

Assign Key to Existing Array

Assuming i have a JSON array like this example below :
[{"type":"food","alias":"meal"}]
And i want to assign this whole array to a particular key called "Dish" for example.
How can i archive this ?
Expected output should be something like :
"Dish":[{"type":"food","alias":"meal"}]
I know how to create new key value pairs but never thought of assigning a key until now.
$json = '[{"type":"food","alias":"meal"}]';
$data = json_decode($json, true);
$data = array('Dish' => $data);
echo json_encode($data);
You could do like this..
<?php
$json = '[{"type":"food","alias":"meal"}]';
$arr = array('dish'=>json_decode($json,true));
echo json_encode($arr);
Demo
echo json_encode(array('Dish' => json_decode($json, true)));
//{"Dish":[{"type":"food","alias":"meal"}]}

Categories