I'm working on a website that I make heavy use of json objects. I have a very, very large json object that contains, from what it looks like, dozens of arrays of arrays of arrays of etc...
I've been doing my normal method of just doing:
$obj = json_decode($json,true);
if( $obj == NULL )
echo "JSON NULL!<br>";
else{
echo "here!!<br>";
foreach( $obj as $key=>$val ){
foreach( $val as $k=>$v){
echo "$k <br>";
}
}
}
But the output is not very meaningful and I find it hard to tell what is the parent of what in terms of being able to access the individual items in a $obj["one"]["two"]["three]" manner.
I've looked around quite a bit and there are many examples of using json_decode in foreach arrays, but all the examples I've found target single-depth arrays. Does anyone know of a way to output the contents in a way that would make it easier to tell what contains what?
Ideally something that tabbing, that's the most visually understandable.
Thanks!
Edit: Thanks for the fast replies! I didn't know about the tags. I wish I could select all of them as "best answer"!
$obj = json_decode($json,true);
echo "<pre>".htmlspecialchars(print_r($obj,TRUE))."</pre>\n";
I agree. This might look good to read
$obj = json_decode($json,true);
echo "<pre>";
print_r( $obj );
echo " </pre>";
This also does the indenting.
I'd suggest something like:
$obj = json_decode($json, true);
echo '<pre>';
echo print_r($obj, true);
echo '</pre>';
I guess you have problem with not knowing how many levels of arrays you have.
You could do a recursive function like this:
function echoarray($obj, $i = 0){
foreach($obj as $key => $val){
if(isarray($val)) echoarray($val, $i++);
else echo "$i - $key: $val <br/>";
}
}
Instead of your original foreach. Variable $i can tell you what level are you on currently.
Take this not as a finished code but as a concept, if it suits your needs.
Basically if current $val is array, function echoarray is called again and again, until $val isn't an array anymore.
Related
I am trying to echo out my array on each line, not bunched together.
I have tried <br />, this only show's on the front end, but when you look at HTML code. Its still clumped together.
$arrays = [];
$arrays[] = "Good";
$arrays[] = "Bad";
foreach ($arrays as $array){
echo $array;
}
Result:
GoodBad
Want Result:
Good
Bad
Short of using print_r, to quickly get your desired result, just make this small change:
echo $array."\n";
Make sure it's double-quotes and it will add a new line.
(That would do what "<br />" does on HTML)
Try using print_r($arrays). docs here.
Try echo "<pre>; var_dump($arrays); echo "</pre>;
I'm using Kucoin's API to get a list of coins.
Here is the endpoint: https://api.kucoin.com/v1/market/open/coins
And here's my code:
$kucoin_coins = file_get_contents('https://api.kucoin.com/v1/market/open/coins');
$kucoin_coins = json_decode($kucoin_coins, true);
print_r($kucoin_coins);
I can see how to target one coin like so:
echo "name: " . $kucoin_coins['data'][0]['name'];
But I can't see how to loop through them.
How can I loop through each of the "coins" returned here? They are under the "data" part that is returned. I'm sorry, I'm just not seeing how to do it right now. Thank you!
You can loop through the decoded elements using the foreach command:
foreach ($kucoin_coins['data'] as $coin) {
//do your magic here.
}
But I usually prefer using json_decode($kucoin_coins) rather than the one for arrays. I believe this:
$item->attribute;
Is easier to write than this one:
$item['attribute'];
foreach($kucoin_coins['data'] as $data) {
echo $data['name']."\n";
}
You can loop through your data using foreach() like this
<?php
$kucoin_coins = file_get_contents('https://api.kucoin.com/v1/market/open/coins');
$kucoin_coins = json_decode($kucoin_coins, true);
print '<pre>';
print_r($kucoin_coins);
print '</pre>';
foreach($kucoin_coins['data'] as $key=>$value){
echo $value['name']. "<br/>";
}
?>
See DEMO: http://phpfiddle.org/main/code/q6kt-dctg
I'm trying to parse a json file into a for each loop. The issue is the data is nested in containers with incremented numbers, which is an issue as I can't then just grab each value in the foreach. I've spent a while trying to find a way to get this to work and I've come up empty. Any idea?
Here is the json file tidied up so you can see what I mean - http://www.jsoneditoronline.org/?url=http://ergast.com/api/f1/current/last/results.json
I am trying to get values such as [number] but I also want to get deeper values such as [Driver][code]
<?php
// get ergast json feed for next race
$url = "http://ergast.com/api/f1/current/last/results.json";
// store array in $nextRace
$json = file_get_contents($url);
$nextRace = json_decode($json, TRUE);
$a = 0;
// get array for next race
// get date and figure out how many days remaining
$nextRaceDate = $nextRace['MRData']['RaceTable']['Races']['0']['Results'][' . $a++ . '];
foreach ($nextRaceDate['data'] as $key=>$val) {
echo $val['number'];
}
?>
While decoding the json there's no need to flatten the object to an Associative array. Just use it how it is supposed to be used.
$nextRace = json_decode($json);
$nextRaceDate = $nextRace->MRData->RaceTable->Races[0]->Results;
foreach($nextRaceDate as $race){
echo 'Race number : ' . $race->number . '<br>';
echo 'Race Points : ' . $race->points. '<br>';
echo '====================' . '<br>';
}
CodePad Example
You are nearly correct with your code, you are doing it wrong when you try the $a++. Remove the $a = 0, you won't need it.
Till here you are correct
$nextRaceDate = $nextRace['MRData']['RaceTable']['Races']['0']['Results']
What you have to do next is this
$nextRaceDate = $nextRace['MRData']['RaceTable']['Races']['0']['Results'];
foreach($nextRaceDate as $key => $value){
foreach($value as $key2 => $value2)
print_r($value2);
So, in my code, you are stopping at Results, and then, you want to iterate over all the results, from 0 to X, the first foreach will do that, you have to access $value for that. So, add another foreach to iterate over all the content that $value has.
There you go, I added a print_r to show you that you are iterating over what you wanted.
The problem is how you access to the elements in the nested array.
Here a way to do it:
$mrData = json_decode($json, true)['MRData'];
foreach($nextRace['RaceTable']['Races'] as $race) {
// Here you have access to race's informations
echo $race['raceName'];
echo $race['round'];
// ...
foreach($race['Results'] as $result) {
// And here to a result
echo $result['number'];
echo $result['position'];
// ...
}
}
I don't know where come's from your object, but, if you're sure that you'll get everytime one race, the first loop could be suppressed and use the shortcut:
$race = json_decode($json, true)['MRData']['RaceTable']['Races'][0];
Your problem is that the index must be an integer because the array is non associative. Giving a string, php was looking for the key '$a++', and not the index with the value in $a.
If you need only the number of the first race, try this way
$a = 0;
$nextRaceDate = $nextRace['MRData']['RaceTable']['Races']['0']['Results'][$a];
echo "\n".$nextRaceDate['number'];
maybe you need to iterate in the 'Races' attribute
If you need all, try this way :
$nextRaceDate = $nextRace['MRData']['RaceTable']['Races'];
foreach ($nextRaceDate as $key => $val) {
foreach ($val['Results'] as $val2) {
echo "\nNUMBER " . $val2['number'];
}
}
So I used JSON to obtain a multidimensional array. What I'm trying to do is for each listing in the main part of the array (not sure what the technical term is) access the part of the array that is below. I would then like to echo each one of these links.
As you can probably see I'm trying to scrape the images. How do I go about doing this? I love to learn so some hints at first would be greatly appreciated. Thanks guys!
[url] => http://imgur.com/0q4G4qP
Json code
<?php
$jsonurl = "http://www.reddit.com/r/pics.json";
$data = file_get_contents($jsonurl);
$array = json_decode($data, true);
echo "<pre>";
print_r($array);
echo "</pre>";
I am not entirely sure how to do this. I referenced the php manual on how to access these types of arrays, but I'm a bit lost. Basically for everyone of those children.
You can do this:
foreach ($multi_d_array['data']['children'] as $item) {
echo $item['data']['url'].'<br/>';
}
Use foreach in loops foreach($data as $d) { echo $d['url'] ;}
$content is an arry. when i print_r($content) the result is too long. now i
echo $fenlei=$content['body']['#object']->field_fenlei['zh-hans'][0]['taxonomy_term']->name;
the result of $fenlei is java. but there maybe many values of $fenlei. eg:
$content['body']['#object']->field_fenlei['zh-hans'][0]['taxonomy_term']->name;
$content['body']['#object']->field_fenlei['zh-hans'][1]['taxonomy_term']->name;
$content['body']['#object']->field_fenlei['zh-hans'][2]['taxonomy_term']->name;
......
how to loop out the
$content['body']['#object']->field_fenlei['zh-hans'][1]['taxonomy_term']->name;
$content['body']['#object']->field_fenlei['zh-hans'][2]['taxonomy_term']->name;
value. it too hard for me. :)
You can store the common code and foreach next:
$common = $content['body']['#object']->field_fenlei['zh-hans'];
foreach($common as $key => $value){
echo "{$key}: " . $value['taxonomy_term']->name;
}
If you want to print out large arrays that are difficult to read you can try:
echo '<pre>'.print_r($array, true).'</pre>';
It makes arrays a little more pretty.