Get data from JSON array - php

I have this JSON array data:
[{"region":"Abersee","price":"1.298"},{"region":"Fuschl am See","price":"1.319"},{"region":"St. Gilgen","price":"1.317"},{"region":"Innerschwand","price":"1.321"},{"region":"Mondsee","price":"1.309"},{"region":"Abersee","price":"1.298"},{"region":"Mondsee","price":"1.309"},{"region":"Innerschwand","price":"1.321"},{"region":"Fuschl am See","price":"1.319"},{"region":"St. Gilgen","price":"1.317"},{"region":"Abersee","price":"1.298"},{"region":"Mondsee","price":"1.309"},{"region":"St. Gilgen","price":"1.317"},{"region":"Fuschl am See","price":"1.319"},{"region":"Innerschwand","price":"1.321"},{"region":"Abersee","price":"1.298"},{"region":"St. Gilgen","price":"1.317"},{"region":"Mondsee","price":"1.309"},{"region":"Fuschl am See","price":"1.319"},{"region":"Innerschwand","price":"1.321"},{"region":"Abersee","price":"1.298"},{"region":"Mondsee","price":"1.309"},{"region":"Fuschl am See","price":"1.319"},{"region":"St. Gilgen","price":"1.317"},{"region":"Innerschwand","price":"1.321"},{"region":"Abersee","price":"1.298"},{"region":"Fuschl am See","price":"1.319"},{"region":"Mondsee","price":"1.309"},{"region":"St. Gilgen","price":"1.317"},{"region":"Innerschwand","price":"1.321"}]
And I am not sure how to properly get the region and price data out. I tried this:
$array = json_encode($jsondata);
$json = json_decode($array, true);
echo $json['region'];
echo $json['price'];
But nothing appears. Any suggestions?

try this:
$array = json_encode($jsondata);
$json = json_decode($array, true);
foreach($json as $data){
echo $data['region'] . "<br>";
echo $data['price'] . "<br>";
}

The json_encode isn't needed, as you say - you already have that JSON data. Simply decode it, then loop over it. You are currently trying to access the first entry, but the conversion from JSON to PHP will add numeric indexes/array keys to the PHP array which don't exist in the JSON.
foreach over the array:
$jsondata = '[{"region":"Abersee","price":"1.298"},{"region":"Fuschl am See","price":"1.319"},{"region":"St. Gilgen","price":"1.317"},{"region":"Innerschwand","price":"1.321"},{"region":"Mondsee","price":"1.309"},{"region":"Abersee","price":"1.298"},{"region":"Mondsee","price":"1.309"},{"region":"Innerschwand","price":"1.321"},{"region":"Fuschl am See","price":"1.319"},{"region":"St. Gilgen","price":"1.317"},{"region":"Abersee","price":"1.298"},{"region":"Mondsee","price":"1.309"},{"region":"St. Gilgen","price":"1.317"},{"region":"Fuschl am See","price":"1.319"},{"region":"Innerschwand","price":"1.321"},{"region":"Abersee","price":"1.298"},{"region":"St. Gilgen","price":"1.317"},{"region":"Mondsee","price":"1.309"},{"region":"Fuschl am See","price":"1.319"},{"region":"Innerschwand","price":"1.321"},{"region":"Abersee","price":"1.298"},{"region":"Mondsee","price":"1.309"},{"region":"Fuschl am See","price":"1.319"},{"region":"St. Gilgen","price":"1.317"},{"region":"Innerschwand","price":"1.321"},{"region":"Abersee","price":"1.298"},{"region":"Fuschl am See","price":"1.319"},{"region":"Mondsee","price":"1.309"},{"region":"St. Gilgen","price":"1.317"},{"region":"Innerschwand","price":"1.321"}]';
$json = json_decode($jsondata, true);
foreach($json as $each)
echo $each['region'] . ': ' . $each['price'] . PHP_EOL;
Example
Edit: a print_r of the decoded array (as mentioned by Marcin Orlowski) would show you its structure in PHP, similar to this:
Array
(
[0] => Array
(
[region] => Abersee
[price] => 1.298
)
[1] => Array
(
[region] => Fuschl am See
[price] => 1.319
)

Related

Storing array in db

I need to create an array of keys and store it in a db table.
$myArr = array();
foreach($keys AS $key) {
$myArr[$r->id] = $r->key;
}
before storing it I serialize it
$db_arr = serialize($myjArr);
Later I need to get the stores array and loop through it to perform some action. However, when I unserialize stored array and do print_r my output looks like this:
Array ( [5981] => 7u7Dj [5982] => mVmx4 )
It appears that the array is malformed. What am I missing?
You should take a look at this, I think you may need to unserialize the data before trying to use it php unserialize
$array = unserialize($serialized_array);
Here is an example
$original = [
"who" => "you",
"me" => "yes"
];
echo "<pre>";
print_r($original);
echo "</pre>";
$ser = serialize($original);
echo "<pre>";
print_r($ser);
echo "</pre>";
$un = unserialize($ser);
echo "<pre>";
print_r($un);
echo "</pre>";

Count number of items in array

This is my code.
I am trying to get number of trade offers through steam API.
I can get an array but i dont know how to count number of items from this array
<?php
$json_url = "http://api.steampowered.com/IEconService/GetTradeOffers/v0001/?key=KEY&get_received_offers=1&active_only=1";
$json = file_get_contents($json_url);
$data = json_decode($json, TRUE);
echo '<pre>' . print_r($data, true) . '</pre>';
How can I get the number of [trade_offers_recived] ? Currently there are 2 trade offers recived (0 and 1)
Your $data array contains "response" arrays, and these "trade_offers_received" arrays. So try this:
$numtradeoffers = count($data['response']['trade_offers_received']);
Function count can be used even for sub-array of your array.
So if you need count of elements in a sub-array, which is under key 'trade_offers_recived' which is in turn under key response:
echo count($data['response']['trade_offers_received']);
As you have linked above your array looks like this:
Array
(
[response] => Array
(
[trade_offers_received] => Array
(
[0] => Array
...
So you just need to do the count on the trade_offers_received key:
<?php
print count($data['response']['trade_offers_received']);

How to display Json Data in PHP?

I have following JSON Data and I tried to display Json data using PHP but it did not display result. Here is my JSON Data
$ads={"ReferenceNo":"KWPOG0QoXU","Message":"SUCCESS","Status":1,"ResponseStatus":200}
I tried following code but it did not work.
$ads1 = json_decode($ads);
echo $ads1->ReferenceNo;
Kindly help me how to display result in PHP. Thanks in advance.
You should parse data as string & then do like this:
$json = '{"ReferenceNo":"KWPOG0QoXU","Message":"SUCCESS","Status":1,"ResponseStatus":200}';
$array = json_decode($json, true);
echo '<pre>'; print_r($array);
Output:
Array
(
[ReferenceNo] => KWPOG0QoXU
[Message] => SUCCESS
[Status] => 1
[ResponseStatus] => 200
)
To get Data, Code like this:
echo $array['ReferenceNo'];
Let me know for further help.
For people interested in pulling data from a location, instead of adding the json on the file, use the following;
$json = file_get_contents('MYLOCATION.json');
$array = json_decode($json, true);
echo '<pre>'; print_r($array);
happy coding :)

json decode/encode repeated array

hey ive managed to decode the encode json i created but when i try to print the decoded array it repeats the same username ( the last one on the list ) over and over again. what i want is that all the users are desplayed
this is the code for the encoded json array
$query =
"SELECT
userid,
username,
password,
email
FROM Users ORDER BY userid";
$results = mysqli_query($connection,$query);
The encoded array code below
<?php
echo "Data with Json Encoding";
foreach($results as $row){
$encode = json_encode($row, true);
echo '<pre>';print_r($encode); echo '</pre>';
}
?>
the decoded array code below
<?php
echo "Data with Json Decoding";
foreach($results as $row){
$decode = json_decode($encode, true);
echo '<pre>'; print_r($decode);'</pre>';
}
this is the result of the code Data with Json Decoding
Array
(
[userid] => 239
[username] => desposit4221
[password] => 699e5fae54df4c82314e42dd86c4d383
[email] => ad471993#hotmail.com
)
Array
(
[userid] => 239
[username] => desposit4221
[password] => 699e5fae54df4c82314e42dd86c4d383
[email] => ad471993#hotmail.com
)
it's this over and over again, it should be the list of my users
any help would be greatly appreciated
echo "Data with Json Encoding";
$encodedResults = array();
foreach($results as $row){
$encode = json_encode($row, true);
echo '<pre>';print_r($encode); echo '</pre>';
$encodedResults[] = $encode;
}
?>
echo "Data with Json Decoding";
foreach($encodedResults as $row){
$decode = json_decode($row, true);
echo '<pre>'; print_r($decode);'</pre>';
}
If you put the line
$encode = json_encode($row, true);
into your second loop just after the foreach line, you should get the results you expect. It's a reasonable way to explore the datamanagement aspects of php. Good luck in your projects!
Encode your array:
echo "Data with Json Encoding";
$encoded_datas = json_encode($results);
echo $encoded_datas;
Decode the string into an array:
echo "Data with Json Decoding";
$decoded_datas = json_decode($encoded_datas, true);
echo '<pre>';
print_r($decoded_datas);
echo '</pre>';
You don't need to encode (and then decode) your array row by row.
Plus, as explained in comments and as shown in costa's answer, your code didn't work because you were decoding the same string each time: your $encoded variable contains the last value you put in it (the last row you encoded).

Problems decoding returned JSON data as an object

Im not sure how to exactly get values (access objects and show them on page, or store as variables, etc. just I want to get those IDs (9473, 5649, 7953 .......) from JSON output.
Adding the URL which I am decoding, so you can take a look at it, cos Im really confused. Either I got undefined strClass or non-object error :/
The source API URL is:
api.worldoftanks.eu/wot/account/tanks/?application_id=demo&fields=tank_id&account_id=503066565
Function to get content from URL:
function get_url_contents($url){
$crl = curl_init();
$timeout = 5;
curl_setopt ($crl, CURLOPT_URL,$url);
curl_setopt ($crl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($crl, CURLOPT_CONNECTTIMEOUT, $timeout);
$ret = curl_exec($crl);
curl_close($crl);
return $ret;
}
This is print of JSON return I get (1, 2 ......... 89):
stdClass Object
(
[status] => ok
[count] => 1
[data] => stdClass Object
(
[503066565] => Array
(
[0] => stdClass Object
(
[tank_id] => 9473
)
[1] => stdClass Object
(
[tank_id] => 5649
)
[2] => stdClass Object
(
[tank_id] => 7953
)
[89] => stdClass Object
(
[tank_id] => 64817
)
)
)
)
This is raw JSON output (its much longer, but its mainly same, just more tank_ids there):
{"status":"ok","count":1,"data":{"503066565":[{"tank_id":9473},{"tank_id":5649},{"tank_id":7953},{"tank_id":64817}]}}
I tried to get data from it in couple of ways, but problem is, that ID (503066565) is Array and every time I get error about non-object data or Undefined property: stdClass:
Im used to get data from JSON when there is no array, so Im little bit confused now.
Also I use PHP.
Commented code is sample of things I tried (and I tried like 20 possible options that came to my mind), but I dont work with JSON output often, so I need your help.
$wg_id = "503066565";
$wot = json_decode(get_url_contents("URL"));
//$tank_id = $wot->data->$wg_id->in_garage;
/*
$tank_id = $wot->data->$wg_id['in_garage'];
foreach ($wot as $i){
echo $i['tank_id'];
}
*/
echo $tank_id;
How can I get all those data out (maybe to array)? I need them to compare those IDs when selecting stuff from DB. Also there might be another value in_garage, is there option to add it to array and know which values are together (you know, each in_garage is for specific tank_id).
Pass true as the second argument to json_decode and those objects will be converted to arrays.
$wg_id is a variable, when you use it as a property, you have to do with:
$wot->data->{$wg_id}
Or you could decode it to array by setting the second parameter of json_decode to true.
$wot = json_decode(get_url_contents("URL"), true);
Then the result will be an array.
you could access it by like $wot['data'][$wg_id]
Seems like you have a JSON object that has arrays in it with objects in them. So based on the structure you are showing try this instead. I also have added an option to json_decode to return the results as an array which might be easier to understand for direct access.
// $json = '{"status":"ok","count":1,"data":{"503066565":[{"tank_id":9473},{"tank_id":5649},{"tank_id":7953},{"tank_id":7697},{"tank_id":2625},{"tank_id":2817},{"tank_id":1553},{"tank_id":8721},{"tank_id":5377},{"tank_id":3137},{"tank_id":8977},{"tank_id":3857},{"tank_id":17},{"tank_id":55297},{"tank_id":7185},{"tank_id":10497},{"tank_id":1041},{"tank_id":14145},{"tank_id":5185},{"tank_id":4929},{"tank_id":10817},{"tank_id":52737},{"tank_id":10513},{"tank_id":11777},{"tank_id":11521},{"tank_id":273},{"tank_id":849},{"tank_id":10769},{"tank_id":1809},{"tank_id":12049},{"tank_id":513},{"tank_id":12097},{"tank_id":10529},{"tank_id":11585},{"tank_id":2561},{"tank_id":6657},{"tank_id":4369},{"tank_id":16145},{"tank_id":6977},{"tank_id":545},{"tank_id":6673},{"tank_id":529},{"tank_id":1793},{"tank_id":5137},{"tank_id":6721},{"tank_id":3905},{"tank_id":12561},{"tank_id":51457},{"tank_id":11553},{"tank_id":11281},{"tank_id":4353},{"tank_id":10049},{"tank_id":11265},{"tank_id":11793},{"tank_id":1537},{"tank_id":6465},{"tank_id":2049},{"tank_id":16641},{"tank_id":1089},{"tank_id":2113},{"tank_id":4625},{"tank_id":1},{"tank_id":54545},{"tank_id":51489},{"tank_id":9793},{"tank_id":11537},{"tank_id":2897},{"tank_id":1825},{"tank_id":2881},{"tank_id":6401},{"tank_id":289},{"tank_id":7761},{"tank_id":2385},{"tank_id":53537},{"tank_id":769},{"tank_id":51713},{"tank_id":5393},{"tank_id":1025},{"tank_id":3329},{"tank_id":6177},{"tank_id":3073},{"tank_id":785},{"tank_id":3089},{"tank_id":3105},{"tank_id":5153},{"tank_id":81},{"tank_id":51985},{"tank_id":609},{"tank_id":56577},{"tank_id":64817}]}}';
$url='http://api.worldoftanks.eu/wot/account/tanks/?application_id=demo&fields=tank_id&account_id=503066565';
$json = file_get_contents($url);
$wot_object = json_decode($json);
$wg_id = "503066565";
// This rolls through them as objects.
echo '<b>Object Access</b><br />';
foreach ($wot_object->data->$wg_id as $key => $value) {
echo $key . ' | ' . $value->tank_id . '<br />';
}
echo '<br />';
// Or add the 'true' option to 'json_decode()' to return an array.
$wot_array = json_decode($json, true);
$wg_id = "503066565";
echo '<b>Array Access</b><br />';
foreach ($wot_array['data'][$wg_id] as $key => $value) {
echo $key . ' | ' . $value['tank_id'] . '<br />';
}
echo '<br />';
echo '<b>Direct Array Access</b><br />';
// Which allows for simpler direct access like this.
echo $wot_array['data'][$wg_id][0]['tank_id'] . '<br />';
echo $wot_array['data'][$wg_id][1]['tank_id'] . '<br />';
echo $wot_array['data'][$wg_id][2]['tank_id'] . '<br />';
echo $wot_array['data'][$wg_id][89]['tank_id'] . '<br />';
echo '<br />';
I believe this should work:
echo $wot->data->{$wg_id}[0]->tank_id;
or you could iterate on $wot->data->{$wg_id} and access the $item->tank_id.
After trying Giacomo1968’s answer, I looked at my code to find out why his is working and mine not.
I found, that I forgot to include Curl.class.php file.
So you can use my code with function, that can get everything, or Giacomo’s one. But if youll use mine, dont forget to include Curl.class.php file there, or it wont work.
Sorry for stupid question, at least its answered!

Categories