How can I foreach over this piece of json - php

Im trying to iterate over the file https://alexa.rob-balmbra.co.uk/tracker/mapping.json
Im trying to loop over each name as in "4-72", however i want access to its contents and its name.
Im doing a search in its content and when I have matched the code, I need to subsequently get the key as in '4-72', etc...
Every time I use foreach i get the contents of the json file rather than the key and the contents.

//Fetch the JSON file and decode it into an associative array
$json = json_decode( file_get_contents('https://alexa.rob-balmbra.co.uk/tracker/mapping.json'), true );
//This is the code you want to search for
$searchCode = "03013";
//Loop through the json array, get key and data
foreach($json as $key=>$data){
//If the code matches what you're searching for, echo the key out and move past the foreach loop.
if($data["code"] == $searchCode){
echo "The service name is: " . $key;
break;
}
}
//You don't need this here. I just used it so I could see all the codes.
echo '<pre>' . print_r($json, 1) . '</pre>';
The code explained:
Go and get the JSON file from the web page
Decode the JSON file into an associative array so PHP can work on it
Set up a search code
For all the keys, search each code to see if it matches the search code
If there is a match, Show the respective key.

Every time I use foreach i get the contents of the json file rather than the key and the contents.
Have you turned the JSON string into an array?
$jsonValues = json_decode($jsonString,true) ;
foreach($jsonValues as $key=>$data) {
// do your thing here
}

Related

PHP Array inside of an array issue

I'm having some problems getting the data through my PHP loop.
<?php
$url = 'https://www.fibalivestats.com/data/1653309/data.json';
$content = file_get_contents($url);
$json = json_decode($content, true);
?>
<?php
foreach($json['totallds']['sPoints'] as $item); {
echo $item;
}
?>
The error I'm getting is an array to string conversion error. What I'm trying to get is the data from the sPoints array that will give me a Top 5 points scorers for a basketball game.
I'll build a table for this in HTML later but for now, it's not displaying the data at all and I'm getting errors. I feel like I may have confused arrays and strings too. Any thoughts about what I'm doing wrong? JSON file can be found in the $url variable.
Also if it helps, here's the link to where I have gotten the data from and what context the Top 5 is from https://www.fibalivestats.com/u/NSS/1653309/lds.html
Thanks!
Your $item is an array, so you can't just echo it like that. You can, however, echo its columns, for example:
foreach($json['totallds']['sPoints'] as $item) {
echo $item['firstName'] . ' ' . $item['familyName'];
}
Notice the removed semicolon between the foreach () and {.
Well, array to string conversion error means you're trying to echo an array.
If you see the return of the url you are looking at, you can verify that the "sPoints" key returns an array with several objects.
Try to change echo to print_r or var_dump to view entire data or complete your business logic.
Try changing:
echo $item;
to:
var_dump($item);

Finding titles in JSON

I currently have this large JSON file: hastebin
But just want the titles of the posts.
I've tried this...
$json = $page;
$o = json_decode($json, true);
echo($json);
$titles = $o["*"]["*"]["*"]["*"]["title"];
var_dump($titles);
But it isn't working - it's returning NULL! Sometimes it just doesn't return anything.
If anyone is wondering, yes this is from Reddit.
This should do it:
$titles = array_map(function($post) {
return $post['data']['title'];
}, $o['data']['children']);
I'm not sure what you expected using "x" indices, but you should probably read about arrays.
PHP can't use wildcards like * in array keys. Whatever string you use to reference the key, it's going to try to find a key with that exact string. So what you tried can't work because there aren't any * keys.
You can get it by iterating all the levels, or iterating the outer level and referring to the proper nested key. But if you're just looking for all instances of 'title' a recursive method may be an easier way to get them.
array_walk_recursive($o, function($value, $key) use (&$titles) {
if ($key == 'title') $result[] = $value;
});
var_dump($titles);
This will get any value of 'title' regardless of its depth in the array, so if that's not what you want, then you'll need to iterate it and specifically reference the proper ones.
It's very hard to deal directly with such a long JSON document. The returned result from the page is not a valid JSON. It contains some HTML tags, but if you take the posts data and insert it in a file you can do the following according to the structure of your JSON (You can find your JSON in an external link here):
<?php
header("Content-Type:application/json");
$posts=file_get_contents('json.php');
//decode your JSON STRING
$posts=json_decode($posts,true);
//create a title variable to store your titles
$titles=array();
foreach($posts['data']['children'] as $child)
{
array_push($titles,$child['data']['title']);
}
echo json_encode($titles);
?>
You can even use this approach using a URL but ensure that it will return a valid JSON with no html

How to read JSON data in php without knowing key value

I need to read firebase JSON URL in php and then display it.
My firebase has got below .json data:
{"dDsdE4AlB7P5YYd4fWbYTQKCLPh1":{"email":"abhi#gmail.com","name":"abhishek"},
"z1ceiLhdh9YVu7lGnVvqDWoWHFH3":{"email":"ravi#gmail.com","name":"ravish"},
"ghg76JHG8jhkj7GHGJ763kjhFF45":{"email":"John#gmail.com","name":"John"}}
I am able to access "name" field using the key value, as below:-
$url = 'https://xxxx.firebaseio.com/users.json'; // path to JSON file
$data = file_get_contents($url); // put the contents of the file into a variable
$characters = json_decode($data); // decode the JSON feed
echo $characters->dDsdE4AlB7P5YYd4fWbYTQKCLPh1->name;
Now, how to access "name" field without knowing the key value? Because these keys are automatically generated by firebase and could be any value.
Many thanks in advance!
Make an associative array from your json. Then you can traverse it using foreach with keys and values. That way you will have the key value also the associated data to the key.
$characters = json_decode($data, 1);
foreach ($characters as $key => $value) {
echo $key . ' ' . $echo $value['name'];
}
You could also try to get the keys themselves:
array_keys($yourEncodedJson);
This will return all key names in the provided array.
This way, you won't need to loop through them.

GET info from external Array/API/URL using PHP

I have the url http://pubapi.cryptsy.com/api.php?method=singleorderdata&marketid=132 which leads to an array.
I want to get the value of the first 'sellorders' which in this case is: 0.00000048 and store it in the variable $sellorderprice.
Can anyone help?
Thanks.
Just access the url contents thru file_get_contents. Your page actually return a JSON string, to get those values into meaningful data, decode it thru json_decode, after that access the data needed accordingly:
$url = 'http://pubapi.cryptsy.com/api.php?method=singleorderdata&marketid=132';
$data = json_decode(file_get_contents($url), true);
$sellorderprice = $data['return']['DOGE']['sellorders'][0]['price'];
echo $sellorderprice;
That code actually points directly to index zero 0 which gets the first price. If you need to get all items an just simply echo them all you need to iterate all items thru foreach:
foreach($data['return']['DOGE']['sellorders'] as $sellorders) {
echo $sellorders['price'], '<br/>';
}
Its simple, you just have to decode json like this:
$json = file_get_contents("http://pubapi.cryptsy.com/api.php?method=singleorderdata&marketid=132");
$arr = json_decode($json, true);
$sellorderprice = $arr['return']['DOGE']['sellorders'][0]['price'];

Help Decoding JSON

I'm trying to get the "screenshotUrls" string from this piece of json:
$request_url = 'http://itunes.apple.com/search?term=ibooks&country=us&entity=software&limit=1';
$json = file_get_contents($request_url);
$decode = json_decode($json, true);
echo $decode['results'][0]['screenshotUrls'];
But I get only text "Array"
What have I done wrong?
Try
var_dump($decode['results'][0]['screenshotUrls']);
IF you get 'Array' output by PHP that means that you're trying to echo an actual array (or the string 'Array'...). That means you need to get a specific index value.
Since $decode['results']['0']['screenshotUrls'] is an array, if you want just a string (say, delimited by commas), you could use
echo implode(",", $decode['results']['0']['screenshotUrls']);
This will iterate over the array, and return a comma-separated string of all the URLs.
Do a var_dump($decode['results']['0']['screenshotUrls']). You'll find that the ['screenshotUrls'] is actually an Array, containing one or more URLs (hence the plural 'urls' in its name).
There's nothing wrong with your code so far, but $decode['results'][0]['screenshotUrls'] is an array of all the URLs to screenshots. To go through each one individualy, you need to do:
forearch ($decode['results'][0]['screenshotUrls'] as $url) {
// Do stuff here
}

Categories