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
Related
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'];
}
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";
}
}
Assume that I have below json response fetched from an API.
{
"owner": "Jane Doe",
"pets": [
{
"color": "white",
"type": "cat"
},
{
"color": "black",
"type": "dog"
}
]
}
From the below PHP code I have converted the json string into a json object. And displayed the pet types.
$jsonObject = json_decode($json);
foreach($jsonObject->pets as $pets){
echo 'Pet type:'.$pets->type.'</br>';
}
However in some cases the response json from the API is in below format
{
"owner": "John Doe",
"pets": {
"color": "white",
"type": "cat"
}
}
in this case above php foreach iteration fails with below message
*Notice: Trying to get property of non-object *
I'm looking for a easy way to do this because the actual json response which i'm handling has lot of these occurrences.
You need to check whether $jsonObject->pets is an array or object. If it's an object, replace it with an array containing that object, then the loop will work.
if (!is_array($jsonObject->pets)) {
$jsonObject->pets = array($jsonObject->pets);
}
You could also do it with a conditional in the foreach:
foreach (is_array($jsonObject->pets) ? $jsonObject->pets : [jsonObject->pets] as $pet) {
...
}
If you don't want to have to write all that every time, you could put it in a function:
function as_array($x) {
return is_array($x) ? $x : [x];
}
and then use:
foreach (as_array($jsonObject->pets) as $pet) {
...
}
I'd also complain to the API designer. It's ridiculous to return inconsistent data formats like this.
I have the following url:
https://graph.facebook.com/123456/likes?access_token=__ACCESS_TOKEN__&format=json
which I then do:
$likesList = json_decode(file_get_contents("https://graph.facebook.com/123456/likes?access_token=$access_token&format=json"),true);
which produces e.g.
{
"data": [
{
"name": "yo yo yo",
"category": "Entertainer",
"id": "45640987076",
"created_time": "2012-04-18T16:14:09+0000"
},
{
"name": "Tony Smith",
"category": "Musician/band",
"id": "456456456456",
"created_time": "2012-02-22T06:56:18+0000"
},
{
"name": "Stations",
"category": "Company",
"id": "567657567",
"created_time": "2012-01-30T23:08:39+0000"
}
]
}
and I then want to list e.g. all the names returned so:
foreach ($likesList->data as $element2){
$name = $element2[name];
echo $name;
}
But it's empty?
See this visualization of your data structure.
As you are receiving an array, you need $list["data"] and not $list->data. Also don't forget to quote the array key "name".
foreach ($likesList['data'] as $element2){
$name = $element2['name'];
echo $name;
}
After json_decode with parameter true you will have associative array. You can access to value by string key. Like in example above.
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!