Help with php loop - php

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!

Related

PHP access foreach to iterate json data multiple object

I'm facing an error when trying to post JSON data into PHP. I am new at this.
any helps makes good for us
the JSON looks like this:
[
{
"sections": [
{
"section_id": "62",
"section_name": "English Language",
}
]
},
{
"questions": [
{
"section_id": "62",
"questionid": "1231",
},
{
"section_id": "62",
"questionid": "1232",
"time_spent": "0",
"status": "unseen",
"testsession_id": "whqgo41nsyurpi2"
},
{
"section_id": "62",
"questionid": "1233",
}
]
}
]
below is the code I wrote. Please correct the PHP code to access those JSON values.
$data = json_decode(file_get_contents("php://input"),true);
foreach ($data['sections'] as $value){
echo $value[section_id];
}
foreach ($data['questions'] as $value){
echo $value[section_id];
}
You are missing the array aspect of the JSON. The JSON is made up of an array firstly, which contains 2 objects, which have parameters of sections in the first, and questions in the second.
sections and questions are both arrays, which can be iterated over using foreach, which returns each of the elements as an object.
Your code after decoding the JSON should be like this.
foreach ($data[0]['sections'] as $value){
echo $value['section_id'];
}
foreach ($data[1]['questions'] as $value){
echo $value['section_id'];
}

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";
}
}

Decoding and looping through PHP JSON array

I have the following deocoded JSON array.
I need to access the "type" inside the context, as well as I need to loop through each of the values in the payload. How do I do that?
{
"RequestHeader":
{
"mess": "am putting it on my wall....",
"created_time": "2010-08-24T09:01:25+0000"
},
"context" :
{
"type": "friends,circles"
}
"payload" [ {12345},{12345} ,{2345} ]
}
I tried the following, but it doesn't work
$decoded = json_decode($json_string);
for ($i=0;$i<payload.length;++$i)
{
$id=$decoded->payload[$i];
//do some operation with the id
}
First of all the JSON you provided is invalid. Supposedly the valid one should look like this
{
"RequestHeader": {
"mess": "am putting it on my wall....",
"created_time": "2010-08-24T09:01:25+0000"
},
"context": {
"type": "friends,circles"
},
"payload": [
12345,
12345,
2345
]
}
After you've fixed the problem with JSON provider it will be quite easy to access data
<?php
$json = <<<'JSON'
{
"RequestHeader": {
"mess": "am putting it on my wall....",
"created_time": "2010-08-24T09:01:25+0000"
},
"context": {
"type": "friends,circles"
},
"payload": [
12345,
12345,
2345
]
}
JSON;
$data = json_decode($json, true);
$type = $data['context']['type'];
var_dump($type);
foreach($data['payload'] as $id) {
var_dump($id);
}
Remember to make sure you check that the data actually exists before accessing it, e.g. isset($data['context']['type']) unless you are absolutely sure in it's integrity.
When you use json_decode method, the output will be nested arrays
So for example to access context type you need to do the following
echo $decoded["context"]["type"];
And to loop on payload you need to do the following
for ($i=0;$i<$decoded["payload"].length;++$i)
{
$id=$decoded["payload"][$i];
//do some operation with the id
}

navigate through multidimensional PHP array by relative path

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.

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

Categories