Assign Key to Existing Array - php

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"}]}

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

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'];

How to take out int value from JSON object?

I'm working with Laravel 5 right now and I have the following problem. I've got response from DB query:
[{"id":1}]
and I want to take out 1 as int or string. Any ideas?
I've tried to solve this like follows:
$json = (DB query);
$data = json_decode($json);
$final = $data[0]->id;
and response is :
json_decode() expects parameter 1 to be string, array given
This is all you need.
$response = json_decode($response); // Decode the JSON
$string = $response[0]->id; // Save the value of id var
As you say, the string you have is in JSON format, so you need to use json_decode to access it in PHP.
The square brackets refer to an array, and the braces refer to an object within that array, so what you're looking for is the id value of the first element (i.e. element 0) in the array.
<?php
$json = '[{"id":1}]';
$data = json_decode($json);
echo $data[0]->id;
// 1
Try this
$json_array = '[{"id":1}]';
$data = json_decode($json_array);
print_r($data); // To display the result array
You just need to decode it, if I'm not misunderstanding your questions.
$json = '[{"id":1}]';
$decodedObject = json_decode($json);
Then you can loop through the aray and do something with your data:
foreach($decodedObject as $key => $value) {
$id = $value->id;
}
If you're using Laravel, though, why not use Eloquent models?

How to get a thing from a Json text?

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'];
?>

How to loop through this json decoded data in PHP?

I've have this list of products in JSON that needs to be decoded:
"[{"productId":"epIJp9","name":"Product A","amount":"5","identifier":"242"},{"productId":"a93fHL","name":"Product B","amount":"2","identifier":"985"}]"
After I decode it in PHP with json_decode(), I have no idea what kind of structure the output is. I assumed that it would be an array, but after I ask for count() it says its "0". How can I loop through this data so that I get the attributes of each product on the list.
Thanks!
To convert json to an array use
json_decode($json, true);
You can use json_decode() It will convert your json into array.
e.g,
$json_array = json_decode($your_json_data); // convert to object array
$json_array = json_decode($your_json_data, true); // convert to array
Then you can loop array variable like,
foreach($json_array as $json){
echo $json['key']; // you can access your key value like this if result is array
echo $json->key; // you can access your key value like this if result is object
}
Try like following codes:
$json_string = '[{"productId":"epIJp9","name":"Product A","amount":"5","identifier":"242"},{"productId":"a93fHL","name":"Product B","amount":"2","identifier":"985"}]';
$array = json_decode($json_string);
foreach ($array as $value)
{
echo $value->productId; // epIJp9
echo $value->name; // Product A
}
Get Count
echo count($array); // 2
Did you check the manual ?
http://www.php.net/manual/en/function.json-decode.php
Or just find some duplicates ?
How to convert JSON string to array
Use GOOGLE.
json_decode($json, true);
Second parameter. If it is true, it will return array.
You can try the code at php fiddle online, works for me
$list = '[{"productId":"epIJp9","name":"Product A","amount":"5","identifier":"242"},{"productId":"a93fHL","name":"Product B","amount":"2","identifier":"985"}]';
$decoded_list = json_decode($list);
echo count($decoded_list);
print_r($decoded_list);

Categories