(PHP, JSON) Foreach [duplicate] - php

This question already has answers here:
How can I combine two strings together in PHP?
(19 answers)
Closed 4 months ago.
I have a question about php and json. Im running this php in foreach loop. But when i get all the tank_id from the json file. I get results like
8011819314145
I want it to display like:
Tank ID: 801
Tank ID: 18193
Tank ID: 14145
What i'm doing wrong? Help me thank you.
Here is my php file:
<?php
$json = file_get_contents("https://api.worldoftanks.eu/wot/account/tanks/?application_id=demo&account_id=521997295");
$json_tank = json_decode($json, TRUE);
foreach ($json_tank['521997295'] as $tank_id) {
echo $tank_id['tank_id'];
}
?>

In a foreach you can get both the key and the value. Take a look at the following pseudo-code
foreach ($array as $key => $value) {
echo $key.': '.$value.'<br />';
}

<?php
$json = file_get_contents("https://api.worldoftanks.eu/wot/account/tanks/?application_id=demo&account_id=521997295");
$json_tank = json_decode($json, TRUE);
echo('<pre>');
//print_r($json_tank);
foreach ($json_tank['data']['521997295'] as $tank_id) {
echo "Tank ID: " . $tank_id['tank_id'] . '<br/>';
}

You just need to format output as you want.
<?php
$json = file_get_contents("https://api.worldoftanks.eu/wot/account/tanks/?application_id=demo&account_id=521997295");
$json_tank = json_decode($json, TRUE);
foreach ($json_tank['521997295'] as $tank_id) {
echo 'Tank ID: '.$tank_id['tank_id'].' ';
}
?>

Related

How to read json array using php foreach? [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 3 years ago.
I want to get id,competitionId,competitionDisplayName of games in the JSON data.My current code doesn't output anything could any one tell me what i am doing wrong.Thanks
$json_string = 'https://webws.365scores.com/web/games/?langId=27&timezoneName=Asia/Hebron&userCountryId=-1&appTypeId=5&sports=1&startDate=17/08/2019&endDate=17/08/2019';
$json = file_get_contents($json_string);
$array = json_decode($json);
foreach($array as $values)
{
$output = $values->games['competitionDisplayName'] . "\n";
}
echo $output;
Try this:
<?php
$json_string = 'https://webws.365scores.com/web/games/?langId=27&timezoneName=Asia/Hebron&userCountryId=-1&appTypeId=5&sports=1&startDate=17/08/2019&endDate=17/08/2019';
$json = file_get_contents($json_string);
$result = json_decode($json);
foreach ($result->games as $game) {
$output .= $game->competitionDisplayName . "\n";
}
echo $output;
I checked your url, the data coming in for games is an array, so you need to loop through that to get the values of each game.
$array = json_decode($json);
foreach($array->games as $game){
$output = $game->competitionDisplayName;
prinr_r($output);
}

Working with json data returned by web service [duplicate]

This question already has answers here:
How to convert a string to JSON object in PHP
(6 answers)
Closed 4 years ago.
I have created a Soap client to request data from web services and the returned data is displayed like this with my CodeIgniter function"
{"GetCodeResult":
{
"Selling":"1000.67114",
"Buying":"9000.65789"
}
}
but I want to format them like this by removing the getCodeResult
{"selling":"1000.67114","Buying":"9000.65789"}
I hope this may help you.
<?php
$jsonData = '{"GetCodeResult":
{
"Selling":"1000.67114",
"Buying":"9000.65789"
}
}';
$data = json_decode($jsonData, true);
$arr_index = array();
foreach ($data as $key => $value) {
$arr_index = $value;
}
echo json_encode($arr_index, true);
?>
Thanks.
If you want to get only the values of selling and buying means, try like below.
<?php
$jsonData = '{"GetCodeResult":
{
"Selling":"1000.67114",
"Buying":"9000.65789"
}
}';
$data = json_decode($jsonData, true);
$arr_index = array();
foreach ($data as $key => $value) {
if($key == 'GetCodeResult'){
$arr_index = $value;
}
}
foreach($arr_index as $values){
$finalVal[] = $values;
}
echo json_encode($finalVal, true);
?>
Decode to array and return only the 'GetCodeResult' then json_encode it.
echo json_encode(json_decode($json, true)['GetCodeResult']);
//{"Selling":"1000.67114","Buying":"9000.65789"}
https://3v4l.org/59RSc
To only echo the values you can assign them to variables using list and array_values.
list($selling, $buying) = array_values(json_decode($json, true)['GetCodeResult']);
echo $selling .PHP_EOL;
echo $buying .PHP_EOL;
//1000.67114
//9000.65789
https://3v4l.org/T5GNg

Retrieve first element of JSON with php [duplicate]

This question already has answers here:
Parsing JSON in PHP
(2 answers)
Closed 5 years ago.
I got a JSON from a web site in the raw format:
{"A_B":{"id":7,"last":"0.00000038"},"A_C":{"id":8,"last":"0.00001938"}, ... }
How do I get the A_B and A_C??? I do not know what A_B and A_C could be.
Try the following.
$json = file_get_contents("your json data");
$arr = json_decode($json, true);
foreach ($arr as $key=>$val) {
var_dump($key);
}
Finally, var_dump($key) displays A_B and A_C.
Suppose you have that raw json in some variable, say $yourJson
First, parse your json. $parsedJson = json_decode($yourJson, true)
Then run a foreach loop and stop after 2 iterations, You will (hopefully) get the right key-value pair.
$i = 0;
$extractedValues = [];
foreach ($parsedJson as $key => $value) {
$extractedValues[$key] = $value; $i++;
if ($i === 2) {
break;
}
}
Now, $extractedValues contains only two elements found from the first two iterations.
$data = json_decode("Your json variable");
foreach($data as $value){
echo $value; // here you receive your desire value.
}
Try this:
$json = '{"A_B":{"id":7,"last":"0.00000038"},"A_C":{"id":8,"last":"0.00001938"}}';
$dataArray = json_decode($json, true);
$arrayKeys = array_keys($dataArray); // in your case A_B and A_C
and if you want to get their values then:
foreach($dataArray as $data) {
foreach($data as $key => $value) {
echo $key . ": " . $value . PHP_EOL;
}
}
var $jsonObj = json_decode('{"A_B":{"id":7,"last":"0.00000038"}}')
print $jsonObj->{'A_B'}

Extract json data with php doesnt works [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 5 years ago.
I have json data like this:
{"result":{"total":19,"hits":[{"keyword":"sidney webb"},{"keyword":"dr webb"}]},"status_msg":"OK","status_code":200,"left_lines":1196851}
I need to extract from json only keywords. I try without success with code:
$json = '{"result":{"total":19,"hits":[{"keyword":"sidney webb"},{"keyword":"dr webb"}]},"status_msg":"OK","status_code":200,"left_lines":1196851}';
foreach ($json['result'] as $keywords)
{
echo $keywords['result']['keyword'];
}
Seems, you forgot to decode the string with json_decode. In addition, your likely would to loop over [result][hits] and not just [result]
$json = '{"result":{"total":19,"hits":[{"keyword":"sidney webb"},{"keyword":"dr webb"}]},"status_msg":"OK","status_code":200,"left_lines":1196851}';
$json = json_decode($json, true);
foreach ($json['result']['hits'] as $hit)
{
echo $hit['keyword'];
}
TRY
$json = '{"result":{"total":19,"hits":[{"keyword":"sidney webb"},{"keyword":"dr webb"}]},"status_msg":"OK","status_code":200,"left_lines":1196851}';
$jsonp =json_decode($json,TRUE);
foreach ($jsonp['result'] as $val)
{
if(is_array($val) ){
foreach ($val as $k)
{
echo $k['keyword'];
}
}
}

Get data from JSON file with PHP [duplicate]

This question already has answers here:
How to loop through PHP object with dynamic keys [duplicate]
(16 answers)
Closed 4 years ago.
I'm trying to get data from the following JSON file using PHP. I specifically want "temperatureMin" and "temperatureMax".
It's probably really simple, but I have no idea how to do this. I'm stuck on what to do after file_get_contents("file.json"). Some help would be greatly appreciated!
{
"daily": {
"summary": "No precipitation for the week; temperatures rising to 6° on Tuesday.",
"icon": "clear-day",
"data": [
{
"time": 1383458400,
"summary": "Mostly cloudy throughout the day.",
"icon": "partly-cloudy-day",
"sunriseTime": 1383491266,
"sunsetTime": 1383523844,
"temperatureMin": -3.46,
"temperatureMinTime": 1383544800,
"temperatureMax": -1.12,
"temperatureMaxTime": 1383458400,
}
]
}
}
Get the content of the JSON file using file_get_contents():
$str = file_get_contents('http://example.com/example.json/');
Now decode the JSON using json_decode():
$json = json_decode($str, true); // decode the JSON into an associative array
You have an associative array containing all the information. To figure out how to access the values you need, you can do the following:
echo '<pre>' . print_r($json, true) . '</pre>';
This will print out the contents of the array in a nice readable format. Note that the second parameter is set to true in order to let print_r() know that the output should be returned (rather than just printed to screen). Then, you access the elements you want, like so:
$temperatureMin = $json['daily']['data'][0]['temperatureMin'];
$temperatureMax = $json['daily']['data'][0]['temperatureMax'];
Or loop through the array however you wish:
foreach ($json['daily']['data'] as $field => $value) {
// Use $field and $value here
}
Demo!
Use json_decode to transform your JSON into a PHP array. Example:
$json = '{"a":"b"}';
$array = json_decode($json, true);
echo $array['a']; // b
Try:
$data = file_get_contents ("file.json");
$json = json_decode($data, true);
foreach ($json as $key => $value) {
if (!is_array($value)) {
echo $key . '=>' . $value . '<br/>';
} else {
foreach ($value as $key => $val) {
echo $key . '=>' . $val . '<br/>';
}
}
}

Categories