Get information from JSON - php

So currently I am doing this..
function get_info($data)
{
$json = file_get_contents("http://site.com/".$data.".json");
$output = json_decode($json, true);
return $output;
}
which is fine and returns everything like this:
array(1) { ["allocation"]=> array(20) { ["carrier_ocn"]=> string(4) "6664" ["available_on"]=> NULL ["status"]=> string(9) "allocated" ["access_type"]=> string(8) "wireless" ["ratecenter"]=> string(9) "CHARLOTTE" ["lat"]=> float(35.2270869) ["contaminations"]=> NULL ["city"]=> string(9) "CHARLOTTE" ["lng"]=> float(-80.8431267) ["current_on"]=> string(10) "2010-04-28" ["block_code"]=> NULL ["npa"]=> int(704) ["geo_precision"]=> int(4) ["nxx"]=> int(291) ["assigned_on"]=> NULL ["country"]=> string(2) "US" ["region"]=> string(2) "NC" ["ratecenter_formatted"]=> string(9) "Charlotte" ["carrier"]=> string(20) "SPRINT SPECTRUM L.P." ["effective_on"]=> NULL } }
How can I make that return only selected values like "ratecenter_formatted". I just want to get "Charlotte" from the above dump. How would I do this?
Thank you in advance!

Hmmm, just fish it out from the array? json_decode() on a JSON array will give you a PHP array that you can use just like any other array in PHP (in this case an associative one).
$output = get_info($data);
echo $output['allocation']['ratecenter_formatted'];

You would still need to decode the entire JSON string to get single values from it, there's no way to decode only certain values.
You could just return the values you want in the php function:
function get_info($data)
{
$json = file_get_contents("http://site.com/".$data.".json");
$output = json_decode($json, true);
return array(
'ratecenter_formatted' => $output['allocation']['ratecenter_formatted']
);
}

Related

Retrieving data from a multidimensional array object stdClass

How can I get out of this likeCount? Thanks cause I have no idea how to do it
https://gdata.youtube.com/feeds/api/videos/f4LxBKN9ank?v=2&alt=jsonc
The array
object(stdClass)#1 (2) {
["apiVersion"]=>
string(3) "2.1"
["data"]=>
object(stdClass)#2 (19) {
["id"]=>
string(11) "f4LxBKN9ank"
["uploaded"]=>
string(24) "2014-01-26T02:34:24.000Z"
["title"]=>
string(25) "League of Legends : Worth"
["content"]=>
object(stdClass)#5 (3) {
["5"]=>
string(74) "https://www.youtube.com/v/f4LxBKN9ank?version=3&f=videos&app=youtube_gdata"
["1"]=>
string(102) "rtsp://r5---sn-4g57kuee.c.youtube.com/CiILENy73wIaGQl5an2jBPGCfxMYDSANFEgGUgZ2aWRlb3MM/0/0/0/video.3gp"
["6"]=>
string(102) "rtsp://r5---sn-4g57kuee.c.youtube.com/CiILENy73wIaGQl5an2jBPGCfxMYESARFEgGUgZ2aWRlb3MM/0/0/0/video.3gp"
}
["duration"]=>
int(78)
["aspectRatio"]=>
string(10) "widescreen"
["rating"]=>
float(4.921824)
["likeCount"]=>
string(5) "14147"
["ratingCount"]=>
int(14429)
["viewCount"]=>
int(678017)
}
}
You can do like that.
<?php
$data = #file_get_contents("http://gdata.youtube.com/feeds/api/videos/f4LxBKN9ank?v=2&alt=jsonc");
$realdata = json_decode($data);
$likecount = $realdata->data->likeCount;
// Sample data
$data = '{"apiVersion":"2.1","data":{"id":"f4LxBKN9ank","uploaded":"2014-01-26T02:34:24.000Z","updated":"2014-03-01T16:48:02.000Z","uploader":"videogamedunkey","category":"Comedy","title":"League of Legends : Worth","description":"Allow 3-5 weeks for your burrito to arrive.\n\nhttps://www.youtube.com/watch?v=YxeOLw1npuo&list=FLsvn_Po0SmunchJYOWpOxMg&index=1","thumbnail":{"sqDefault":"https://i1.ytimg.com/vi/f4LxBKN9ank/default.jpg","hqDefault":"https://i1.ytimg.com/vi/f4LxBKN9ank/hqdefault.jpg"},"player":{"default":"https://www.youtube.com/watch?v=f4LxBKN9ank&feature=youtube_gdata_player","mobile":"https://m.youtube.com/details?v=f4LxBKN9ank"},"content":{"5":"https://www.youtube.com/v/f4LxBKN9ank?version=3&f=videos&app=youtube_gdata","1":"rtsp://r5---sn-jc47eu7e.c.youtube.com/CiILENy73wIaGQl5an2jBPGCfxMYDSANFEgGUgZ2aWRlb3MM/0/0/0/video.3gp","6":"rtsp://r5---sn-jc47eu7e.c.youtube.com/CiILENy73wIaGQl5an2jBPGCfxMYESARFEgGUgZ2aWRlb3MM/0/0/0/video.3gp"},"duration":78,"aspectRatio":"widescreen","rating":4.921824,"likeCount":"14147","ratingCount":14429,"viewCount":678049,"favoriteCount":0,"commentCount":1497,"accessControl":{"comment":"allowed","commentVote":"allowed","videoRespond":"moderated","rate":"allowed","embed":"allowed","list":"allowed","autoPlay":"allowed","syndicate":"allowed"}}}';
// Decode $data into an array
$json = json_decode($data, true);
// Get the like count from data/likeCount in the array
$likeCount = $json["data"]["likeCount"];
// Display the likeCount
echo $likeCount; // 14147
$json = json_decode($data, true) decodes the data in $data into an array called $json. This array has a sub-array whose key is "data", and this sub-array contains the like count under the key "likeCount". Therefore, the like count can be accessed by chaining indexes together: $likeCount = $json["data"]["likeCount"])

PHP & JSON: How can I get a value from where another value equals xyz?

I'm receiving a JSON and trying to interpret some values using PHP.
Example snippet from a JSON dump:
["11811"]=>
object(stdClass)#15 (11) {
["parent_area"]=>
NULL
["generation_high"]=>
int(19)
["all_names"]=>
object(stdClass)#16 (0) {
}
["id"]=>
int(11811)
["codes"]=>
object(stdClass)#17 (3) {
["ons"]=>
string(2) "08"
["gss"]=>
string(9) "E15000008"
["unit_id"]=>
string(5) "41421"
}
["name"]=>
string(10) "South East"
["country"]=>
string(1) "E"
["type_name"]=>
string(15) "European region"
["generation_low"]=>
int(1)
["country_name"]=>
string(7) "England"
["type"]=>
string(3) "EUR"
}
As there is lots of (nested) data, I need to obtain the value of ["name"] where ["type_name"] == 'European region'.
Thanks.
You could use array_filter()
$data_array = array(...);
function is_european($data) {
return $data->type_name == 'European region';
}
$filtered = array_filter($data_array,'is_european');
And then use filtered array to obtain values.
Maybe a better way would be to use JsonPath, like this, assuming your array is a result of decoding JSON (object):
$names = jsonPath($data_object, "$.[?(#['type_name'] == 'European region')].name");
Haven't tried this myself, it may need a bit of correction.
Try this:
<?php
$json = JSON_decode(str,true);
$arr = Array();
foreach($json as $f) {
/* eg. $f = $json["11811"] */
if($f['type_name'] == 'European region') {
$arr[] = $f['name'];
}
}
?>

How to access JSON decoded array in PHP

I returned an array of JSON data type from javascript to PHP, I used json_decode($data, true) to convert it to an associative array, but when I try to use it using the associative index, I get the error "Undefined index" The returned data looks like this
array(14) { [0]=> array(4) { ["id"]=> string(3) "597" ["c_name"]=> string(4) "John" ["next_of_kin"]=> string(10) "5874594793" ["seat_no"]=> string(1) "4" }
[1]=> array(4) { ["id"]=> string(3) "599" ["c_name"]=> string(6) "George" ["next_of_kin"]=> string(7) "6544539" ["seat_no"]=> string(1) "2" }
[2]=> array(4) { ["id"]=> string(3) "601" ["c_name"]=> string(5) "Emeka" ["next_of_kin"]=> string(10) "5457394839" ["seat_no"]=> string(1) "9" }
[3]=> array(4) { ["id"]=> string(3) "603" ["c_name"]=> string(8) "Chijioke" ["next_of_kin"]=> string(9) "653487309" ["seat_no"]=> string(1) "1" }
Please, how do I access such array in PHP? Thanks for any suggestion.
As you're passing true as the second parameter to json_decode, in the above example you can retrieve data doing something similar to:
$myArray = json_decode($data, true);
echo $myArray[0]['id']; // Fetches the first ID
echo $myArray[0]['c_name']; // Fetches the first c_name
// ...
echo $myArray[2]['id']; // Fetches the third ID
// etc..
If you do NOT pass true as the second parameter to json_decode it would instead return it as an object:
echo $myArray[0]->id;
$data = json_decode($json, true);
echo $data[0]["c_name"]; // "John"
$data = json_decode($json);
echo $data[0]->c_name; // "John"
$data = json_decode(...);
$firstId = $data[0]["id"];
$secondSeatNo = $data[1]["seat_no"];
Just like this :)
As you're passing true as the second parameter to json_decode, in the above example you can retrieve data doing something similar to:
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
?>
This may help you!
$latlng='{"lat":29.5345741,"lng":75.0342196}';
$latlng=json_decode($latlng,TRUE); // array
echo "Lat=".$latlng['lat'];
echo '<br/>';
echo "Lng=".$latlng['lng'];
echo '<br/>';
$latlng2='{"lat":29.5345741,"lng":75.0342196}';
$latlng2=json_decode($latlng2); // object
echo "Lat=".$latlng2->lat;
echo '<br/>';
echo "Lng=".$latlng2->lng;
echo '<br/>';
When you want to loop into a multiple dimensions array, you can use foreach like this:
foreach($data as $users){
foreach($users as $user){
echo $user['id'].' '.$user['c_name'].' '.$user['seat_no'].'<br/>';
}
}

Create JSON object from PHP MySQL result

I want to create a JSON object from my MySQL results with PHP so I can pass it to JavaScript. I don't quite understand the difference between JSON array and JSON object.
This is how I do it. But is there a better way? This is the array way I believe?
$json = array();
while($r=mysql_fetch_array($res)){
$json['firstname'] = $r['firstname'];
$json['lastname'] = $r['lastname'];
}
echo json_encode($json);
I want to be able to get the info from JavaScript, by selecting all first names only If I wish etc..
you can try this, fetch data and push to array, then echo that array
$info=array();
while($row = mysql_fetch_array($res,MYSQL_ASSOC)){
array_push($info,$row);
}
echo json_encode($info);
would return
array(2) { [0]=> array(3) { ["id"]=> string(1) "1" ["firstname"]=> string(3) "foo" ["lastname"]=> string(3) "bar" } [1]=> array(3) { ["id"]=> string(1) "2" ["firstname"]=> string(3) "foo" ["lastname"]=> string(3) "bar" } }
json
[{"id":"1","firstname":"foo","lastname":"bar"},{"id":"2","firstname":"foo","lastname":"bar"}]
Well this would encode every row, with each row being the JSON Object:
$json = array();
while($r=mysql_fetch_array($res)){
$json[] = $r;
}
echo json_encode($json);

2D arrays in JSON getting converted into a 1D array of objects

I've looked around but haven't found an answer so I figured i would give it an ask myself.
I've noticed that a round trip to JSON converts a 2-D array into a 1D array of Objects.
Is there any way around this or should I just try to work with objects from the beginning (e.g. $test->1->4 ? see example below
$test = array();
$test[0][0] = "0-0";
$test[0][2] = "0-2";
$test[1][1] = "1-1";
$test[1][2] = "1-2";
var_dump($test);
$encoded = json_encode($test);
var_dump($encoded);
$recreated = json_decode($encoded);
var_dump($recreated);
outputs
array(2) {
[0]=>
array(2) {
[0]=>
string(3) "0-0"
[2]=>
string(3) "0-2"
}
[1]=>
array(2) {
[1]=>
string(3) "1-1"
[2]=>
string(3) "1-2"
}
}
string(45) "[{"0":"0-0","2":"0-2"},{"1":"1-1","2":"1-2"}]"
array(2) {
[0]=>
object(stdClass)#19 (2) {
["0"]=>
string(3) "0-0"
["2"]=>
string(3) "0-2"
}
[1]=>
object(stdClass)#20 (2) {
["1"]=>
string(3) "1-1"
["2"]=>
string(3) "1-2"
}
}
This is because you don't have ongoing indexes in your array:
$test = array();
$test[0][0] = "0-0";
$test[0][2] = "0-2";
In this case json_encode() HAS to create an object because there is a numeric key (1) missing.
You can decode it back to an array with json_decode($txt, true), but this is only a work around, not a fix.
By default json_decode will convert the json into objects. You code needs to look like:
$recreated = json_decode($encoded, true);
You can decode as arrays:
$recreated = json_decode($encoded, true);

Categories