navigate through multidimensional PHP array by relative path - php

I'm trying to use some JSON data in my website, but i got stuck while trying to read from.
Getting the data works well:
<?php
$data = json_decode(file_get_contents('http://ddragon.leagueoflegends.com/cdn/5.2.1/data/en_US/champion.json'));
?>
this is a little excerpt of the JSON data, but it lasts out to explain the problem
{
"type": "champion",
"format": "standAloneComplex",
"version": "5.10.1",
"data": {
"Aatrox": {
"version": "5.10.1",
"id": "Aatrox",
"key": "266",
"name": "Aatrox",
"title": "Die Klinge der Düsteren",
"info": {
"attack": 8,
"defense": 4,
"magic": 3,
"difficulty": 4
},
},
"Ahri": {
"version": "5.10.1",
"id": "Ahri",
"key": "103",
"name": "Ahri",
"title": "Die neunschwänzige Füchsin",
"info": {
"attack": 3,
"defense": 4,
"magic": 8,
"difficulty": 5
},
},
}
}
Question: How is it possible, to access the value of "key", without knowing the 'heading' (e.g. "Aatrox") ?
I tried $data->{'data'}[0]->{'key'}, but that doesn't work.
Second Question: I also tried to search for the value of "key", but had no success in building the path with this method in PHP. A try with JavaScript worked well, but I would prefer to have a server-sided solution.
Thanks for your help!

If you want an element at particular 'offset', use
array_values($data->data)[0]->key;
otherwise, use foreach:
foreach ($data->data as $heading=>$data) {
echo "The heading is $heading and key is {$data->key}";
}

Alternative very short way:
<?php
$data = json_decode(file_get_contents('http://ddragon.leagueoflegends.com/cdn/5.2.1/data/en_US/champion.json'), true);
$first = current($data['data']);
More complete example:
<?php
$data = json_decode(file_get_contents('http://ddragon.leagueoflegends.com/cdn/5.2.1/data/en_US/champion.json'));
$key = current($data->data)->key

Personally I prefer to convert JSON object into the more PHP friendly Array.
If you use json_decode(file_get_contents('http://ddragon.leagueoflegends.com/cdn/5.2.1/data/en_US/champion.json')));
You will be able to access the key value with something like this
$champions = json_decode(file_get_contents('http://ddragon.leagueoflegends.com/cdn/5.2.1/data/en_US/champion.json')));
foreach($champions['data'] as $key => $row){
echo $row['key'];
}
This will echo your keys.

Related

Looping through a json file to find a particular value in PHP

My json file look likes
myjson.json
[
{"name":"category_01","data":
[
{"id":"1","word":"ma","given_value":"1"},
{"id":"3","word":"me","given_value":"1"},
] }
[
{"name":"category_02","data":
[
{"id":"1","word":"vea","given_value":"1"},
{"id":"3","word":"ve","given_value":"1"},
] }
So what I want here is, check whether a particular value is in this json array using php. Assume that,
myphp.php
$word = 've';
if this value is in the above array, should find is it in category_01 or category_02. and also want to find given_value of matching word.
I just tried in this way,
$data = file_get_contents ("myjson.json");
$json = json_decode($data, true);
foreach($arr as $item) {
$uses = ($item['word']= $word);
}
This doesn't work. How can I fix this, Please help me!
First of all, the JSON you posted is invalid. I think it should look like this:
[
{
"name": "category_01",
"data": [{
"id": "1",
"word": "ma",
"given_value": "1"
},
{
"id": "3",
"word": "me",
"given_value": "1"
}
]
},
{
"name": "category_02",
"data": [{
"id": "1",
"word": "vea",
"given_value": "1"
},
{
"id": "3",
"word": "ve",
"given_value": "1"
}
]
}
]
Try using on online tool like https://jsonlint.com/ to check your JSON. (if you get errors i recommend build the json again from scratch).
I also recommend checking your json before using it:
if ($arr === null && json_last_error() !== JSON_ERROR_NONE) {
die("incorrect json data");
}
To get your value you have to KNOW how your data looks like and then process it:
foreach($arr as $category) {
foreach($category['data'] as $data) {
if(strstr($data['word'], $word))
echo $category['name'].' '.$data['word'].' '.$data['given_value']."\n";
}
}

Get data from JSON file with PHP (empty result with numbers)

I'm trying to get data from the following JSON file using PHP
I Want To Get All URls (link) ,
http://www.google.com
http://www.bing.com
Json
Here is what I tried
PHP
Thanks
You cannot access an object property using a number, it must be a string.
It is much easier to output json_decode as an array, and access properties that way. To do this, put true as the second parameter.
<?php
$json = '
{
"news": {
"name": "yahoo",
"url": "https://yahoo.com"
},
"links": [
{
"id": "1",
"url": "https://google.com"
},
{
"id": "2",
"url": "https://bing.com"
}
]
}';
$decode = json_decode($json, true);
echo $decode['links'][0]['url'];

php unset in array foreach loop creates an object

I have a big JSON that looks something like this:
{
"bracers": [
{
"id": "Bracers_208",
"name": "Unearthed Boon"
}
],
"offHand": [
{
"id": "Bracers_208",
"name": "Unearthed Boon"
},
{
"id": "Weapon123",
"name": "Some Weapon Boon"
},
{
"id": "Weapon456",
"name": "Some Other Weapon Boon"
}
],
"mainHand": [
{
"id": "Weapon123",
"name": "Some Weapon Boon"
}
]
}
I decode the JSON like this:
$itemDB = json_decode($json, true);
What I want to do now is to remove all entries from offHand that are already in mainHand. So I loop through both, compare the id and unset() the value if there's a match.
foreach($itemDB['offHand'] as $index => $item) {
foreach($itemDB['mainHand'] as $key => $weapon) {
if($item['id'] == $weapon['id']) {
unset($itemDB['offHand'][$index]);
}
}
}
Then I encode it again:
$newJSON = json_encode($itemDB, JSON_PRETTY_PRINT);
The removal of duplicates works, but the offHand array is changed into an object (or assoc array) that looks like this:
{
"bracers": [
{
"id": "Bracers_208",
"name": "Unearthed Boon"
}
],
"offHand": [
"0": {
"id": "Bracers_208",
"name": "Unearthed Boon"
},
"2": {
"id": "Weapon456",
"name": "Some Other Weapon Boon"
}
],
"mainHand": [
{
"id": "Weapon123",
"name": "Some Weapon Boon"
}
]
}
Why does this happen and how can I prevent it?
Edit:
Just to clarify, if I remove the unset function and just do nothing inside that loops ( or just add a property to the objects), the numbered additional keys in the JSON aren't there and the JSON array is fine. That's why I concluded that unset is causing this.
After you're loop ends, add the following line of code to remove the keys from the offHand array element:
$itemDB['offHand'] = array_values($itemDB['offHand']);
As much a I think , by unset, you are removing a part of array, making it non sequential Thus it might be converted into object
I guess the above line was bit unclear, so consider this example,
function ep($f)
{
echo "<br><pre><code>";
print_r($f);
echo "</code></pre><br";
}
$t = array("a","b","c");
ep(json_encode($t));
unset($t[1]);
ep(json_encode($t));
Forget the function ep.On line 1 , we declare a sequential array and print it, as it is sequential it prints as an array. On line 2, we break the sequence. So printing it again , though it is an array, (*it maybe PHP's function does not know how to convert it) it printed as Object

How to read JSON results from PHP

How to access element of below json output using php ..
{
"ISBN:9781430215752": {
"bib_key": "ISBN:9781430215752",
"preview":
"restricted",
"preview_url":
"https://archive.org/details/linuxrecipesforo00kuhn",
"info_url": "https://openlibrary.org/books/OL23936576M/Linux_recipes_for_Oracle_DBAs",
"details": {
"lc_classifications": ["QA76.9.D3 K84 2009"],
"latest_revision": 2,
"ocaid": "linuxrecipesforo00kuhn",
"contributions": ["Kim, Charles.", "Lopuz, Bernard."],
"source_records": ["marc:marc_loc_updates/v37.i44.records.utf8:10470755:1047"],
"title":
"Linux recipes for Oracle DBAs",
"languages": [{
"key": "/languages/eng"
}],
"subjects": ["Linux", "Oracle (Computer file)", "Relational databases", "Database management"],
"publish_country": "cau",
"by_statement": "Darl Kuhn, Charles Kim, Bernard Lopuz.",
"type": {
"key": "/type/edition"
},
"revision": 2,
"other_titles": ["Linux recipes for Oracle DataBase Administrators"],
"publishers": ["Apress", "Distributed to the book trade by Springer-Verlag"],
"last_modified": {
"type": "/type/datetime",
"value": "2014-04-06T06:55:36.956977"
},
"key": "/books/OL23936576M",
"authors": [{
"name": "Darl Kuhn",
"key": "/authors/OL1484587A"
}],
"publish_places": ["Berkeley, CA", "New York"],
"oclc_number": ["243543902"],
"pagination": "xxv, 501 p. :",
"created": {
"type": "/type/datetime",
"value": "2009-11-24T23:42:39.524606"
},
"dewey_decimal_class": ["005.75/65 22", "005.26/8"],
"notes": {
"type": "/type/text",
"value": "Includes index."
},
"number_of_pages": 501,
"isbn_13": ["9781430215752"],
"lccn": ["2009277832"],
"isbn_10": ["1430215755"],
"publish_date": "2008"
}
}
}
I tried using below code,
it doesn't work.
$json = json_decode($body);
echo $json->ISBN:9780980200447->info_url;
It's giving an error..
Is there any other easy way to read all elements?
You are on the right track. : is just an invalid character for a property and must be handled special.
echo $json->{'ISBN:9781430215752'}->info_url;
will get you the expected result.
You may also decode as an associative array
$json = json_decode($body, true);
echo $json['ISBN:9781430215752']['info_url'];
I would probably stick to this approach rather than the object oriented, since encapsulating keys makes code less readable
You must use
echo $json->{'ISBN:9780980200447'}->info_url;
since 'ISBN:9780980200447' is your class name.
Reference: php.net
<?php
$json = '{"foo-bar": 12345}';
$obj = json_decode($json);
print $obj->{'foo-bar'}; // 12345
?>
Use braces like this:
echo $json->{'ISBN:9781430215752'}->info_url;

Help with php loop

i need to extract data from this array of objects
{
"data": [
{
"id": "136104923104306",
"from": {
"name": "GetWith.It",
"category": "Website",
"id": "136132969751208"
},
"message": "Do u know y **LOVE IS BLIND**\nbcoz..\n''ur mom started to love u before seeing ur face''....!",
"updated_time": "2010-10-05T13:41:42+0000",
"comments": {
"data": [
{
"id": "136104923104306_1075253",
"from": {
"name": "Hressence Ec",
"id": "1464305271"
},
"message": "this I would agree..love is surely blind..",
"created_time": "2010-10-12T01:40:47+0000",
}
]
}
}
My current code:
$data=json_decode(file_get_contents('https://myurl/where/this/data/is'));
foreach($data as $dts){
echo "$dts->message";
};
i need to extract the comments ..
and when i try
foreach($data->comments->data as $dts){
echo "$dts->message";
};
it returns null!
help please
Your $data is actually an object with a data property that is an array containing another object with the comments object you are looking for. So:
foreach ($data->data as $item) {
foreach ($item->comments->data as $comment) {
echo $comment->message;
}
}
I suggest you transform it into an associative array:
$data=json_decode(file_get_contents('https://myurl/where/this/data/is'), true);
and have a look at the structure.
I think your loop must look like this:
foreach($data['data'] as $dts) {
echo $dts['message'];
}
Update: Although I was able to fix the JSON (at least it seems to be good now) json_decode still returns null. No clue way. First make sure your JSON string is valid!

Categories