Related
I have the following PHP code (I'll post the important part of it):
// objID
$objects->objID = generateRandomID();
$objects->pointer = array('type'=>'__pointer','objID'=>'dgFg45dG','className'=>'Users');
$jsonStr = file_get_contents($className.'.json'); // This calls a Users.json file stored in my server
$jsonObjs = json_decode($jsonStr, true);
...
$jsonStr = file_get_contents($className.'.json'); // This calls a Users.json file stored in my server
$jsonObjs = json_decode($jsonStr, true);
array_push($jsonObjs, $objects);
// Encode the array back into a JSON string and save it.
$jsonData = json_encode($jsonObjs);
file_put_contents($className.'.json', $jsonData);
// echo JSON data
echo $jsonData;
// ISSUE HERE :(
$jsonStr = file_get_contents($className.'.json');
// Decode the JSON string into a PHP array.
$jsonObjs = json_decode($jsonStr, true);
foreach($jsonObjs as $i=>$obj) {
print_r('<br><br>'.$i.'-- ');
echo
$obj['objID'].', <br>'
.$obj['pointer']["$i"]['objID']. ', '
.$obj['pointer']["$i"]['type']. ', '
.$obj['pointer']["$i"]['className']. '<br><br>'
;
}
// ./ ISSUE
The code above creates a new JSON object into my own Users.json file.
So, when I call this PHP file with a URL string in my browser, just as a test, and I refresh the page a few times, I get the following echo:
0-- VUDjCZX8QX, , ,
1-- 1uWH17OoJP, , ,
[{"objID":"VUDjCZX8QX","pointer":{"type":"__pointer","objID":"dgFg45dG","className":"Users"},"string":"mark","createdOn":"2018-09-17 05:36:49","updatedOn":"2018-09-17 05:36:49","number":111,"boolean":true,"array":["john","sarah"]},{"objID":"1uWH17OoJP","pointer":{"type":"__pointer","objID":"dgFg45dG","className":"Users"},"string":"mark","createdOn":"2018-09-17 05:36:51","updatedOn":"2018-09-17 05:36:51","number":111,"boolean":true,"array":["john","sarah"]},{"objID":"RkubyQPvqR","pointer":{"type":"__pointer","objID":"dgFg45dG","className":"Users"},"string":"mark","createdOn":"2018-09-17 05:36:54","updatedOn":"2018-09-17 05:36:54","number":111,"boolean":true,"array":["john","sarah"]}]
So, what I need to fix is basically the following:
What's the right code to properly get the list of items of the
"pointer" object that's inside each object of my Users.json file?
I try to track the index of my foreach loop, but it doesn't work properly as you can see by the echo posted above when I first execute my PHP code, I get the JSON string of my 1st object, I don't get any print_r(). Then, when I refresh the page a 2nd time, I get the print of the objID string of my 1st object, and again, if I refresh the page a 3rd time, I get the objID of my 2nd object, while there are 3 objects stored in my json file. And so on, in other words, I never get the first object's print info.
What am I doing wrong?
You are passing $i as a string, not as a variable. Use double quotes (") or remove single quotes (') to pass as a variable. This will solve your issue, pointer objects not printing properly.
$obj['pointer'][$i]['objID']
Update
[{"objID":"VUDjCZX8QX","pointer":{"type":"__pointer","objID":"dgFg45dG","className":"Users"},"string":"mark","createdOn":"2018-09-17 05:36:49","updatedOn":"2018-09-17 05:36:49","number":111,"boolean":true,"array":["john","sarah"]},{"objID":"1uWH17OoJP","pointer":{"type":"__pointer","objID":"dgFg45dG","className":"Users"},"string":"mark","createdOn":"2018-09-17 05:36:51","updatedOn":"2018-09-17 05:36:51","number":111,"boolean":true,"array":["john","sarah"]},{"objID":"RkubyQPvqR","pointer":{"type":"__pointer","objID":"dgFg45dG","className":"Users"},"string":"mark","createdOn":"2018-09-17 05:36:54","updatedOn":"2018-09-17 05:36:54","number":111,"boolean":true,"array":["john","sarah"]}]
According to above JSON string, you don't need specify $i.
$obj['pointer']['objID'] should work, since it is associate array.
Thanks to #saumini-navaratnam, I have to use the following foreach:
foreach($jsonObjs as $i=>$obj) {
print_r('<br><br>'.$i.'-- ');
echo
$obj['objID'].', '
.$obj['pointer']['objID']. ', '
.$obj['pointer']['type']. ', '
.$obj['pointer']['className']. '<br><br>'
;
}
In this way, I can properly get the objects of this object:
{"pointer":{"type":"__pointer","objID":"dgFg45dG","className":"Users"}
In fact, here's the echo I get:
[
{"objID":"pkO8NesS5S","pointer":{"type":"__pointer","objID":"dgFg45dG","className":"Users"},"string":"bobby","createdOn":"2018-09-17 07:03:27","updatedOn":"2018-09-17 07:03:27","number":111,"boolean":true,"array":["john","sarah"]},
{"objID":"rdwJl20krC","pointer":{"type":"__pointer","objID":"dgFg45dG","className":"Users"},"string":"bobby","createdOn":"2018-09-17 07:03:31","updatedOn":"2018-09-17 07:03:31","number":111,"boolean":true,"array":["john","sarah"]},
{"objID":"3WspzmuwMK","pointer":{"type":"__pointer","objID":"dgFg45dG","className":"Users"},"string":"bobby","createdOn":"2018-09-17 07:07:39","updatedOn":"2018-09-17 07:07:39","number":111,"boolean":true,"array":["john","sarah"]}
]
0-- pkO8NesS5S, dgFg45dG, __pointer, Users
1-- rdwJl20krC, dgFg45dG, __pointer, Users
2-- 3WspzmuwMK, dgFg45dG, __pointer, Users
I have been stuck in this issue and cant seem to fix it.. I have this JSON STRING
$unBillableArr = ["{'id' : '123','to' : '+923412268656','MsgReceivedFrom' : '03349433314', 'message':'Qwertyy ', 'recdate':'2017-11-20 19:01:49'}"];
I need to convert it into array of object or maybe just one json object.. I have tried doing
json_decode($unBilledArr , true);
It gives me null.
Already tried these solutions as well
Convert a string to JSON object php
https://jonsuh.com/blog/convert-loop-through-json-php-javascript-arrays-objects/
I must be doing something wrong.. cant seem to figure out what..
P.s : This is the response i am getting and i can not do anything about the response.
You are trying to decode an array, either specify the specific item within the array, or make it a string.
For instance:
$unBillableArr = '{"id":"123", "to":"+923412268656", "MsgReceivedFrom":"03349433314", "message":"Qwertyy", "recdate":"2017-11-20 19:01:49"}';
$json = json_decode($unBillableArr, true);
// Or
$unBillableArr = ['{"id":"123", "to":"+923412268656", "MsgReceivedFrom":"03349433314", "message":"Qwertyy", "recdate":"2017-11-20 19:01:49"}'];
$json = json_decode($unBillableArr[0], true);
However, given the string you are receiving does not contain valid JSON and you are unable to control what you receive, I have prepared the following that will replace the single quotes in your JSON, and decode each item into an array:
$unBillableArr = ["{'id' : '123','to' : '+923412268656','MsgReceivedFrom' : '03349433314', 'message':'Qwertyy ', 'recdate':'2017-11-20 19:01:49'}"];
// Loop through each JSON string
$jsonObjects = []; // Change this name...
foreach ($unBillableArr as $jsonString) {
$jsonObjects[] = json_decode(str_replace("'", '"', $jsonString), true);
}
print_r($jsonObjects); // Proof it works
Please bear in mind that I would consider this to be a dirty fix. To fix this properly, you should go back to the source and ensure that the JSON they are returning to you is valid.
Trying to read json Data and I can't get it to work correctly with the following code:
$apiurl = "https://api.hasoffers.com/Apiv3/json?NetworkId=REDACTED&Target=Affiliate_Report&Method=getStats&api_key=REDACTED&fields%5B%5D=Stat.conversions&fields%5B%5D=Stat.unique_clicks&fields%5B%5D=Stat.payout&filters%5BStat.date%5D%5Bconditional%5D=LESS_THAN&filters%5BStat.date%5D%5Bvalues%5D=2016-02-21&filters%5BStat.date%5D%5Bconditional%5D=GREATER_THAN&filters%5BStat.date%5D%5Bvalues%5D=2016-02-21";
$data = json_decode(file_get_contents($apiurl), true);
foreach($data['response']['data'] as $dataline) {
echo "Conversions: {$dataline['Stat']['conversions']} Payout: {$dataline['Stat']['payout']}";
}
The query is generating the following json return, I just can't figure out how to read the stats correctly (it's also looping through 7 lines in the foreach which also makes no sense to me):
{"request":{"Target":"Affiliate_Report","Format":"json","Service":"HasOffers","Version":"2","NetworkId":"REDACTED","Method":"getStats","api_key":"REDACTED","fields":["Stat.conversions","Stat.unique_clicks","Stat.payout"],"filters":{"Stat.date":{"conditional":"GREATER_THAN","values":"2016-02-21"}},"__gaTune":"GA1.2.1289716345.1455904273","__utma":"267117079.1377304869.1455903853.1455904273.1455904273.1","__utmc":"267117079","__utmz":"267117079.1455904273.1.1.utmcsr=developers.hasoffers.com|utmccn=(referral)|utmcmd=referral|utmcct=/","_biz_uid":"1742fd1f613440a4cfbb5a510d1d7def","_biz_nA":"1","_biz_pendingA":"[]","_hp2_id_1318563364":"5257773084071598.0276720083.0714677778","_ga":"GA1.2.1377304869.1455903853"},"response":{"status":1,"httpStatus":200,"data":{"page":1,"current":50,"count":1,"pageCount":1,"data":[{"Stat":{"conversions":"1000","unique_clicks":"1000","payout":"1000.000000"}}],"dbSource":"branddb"},"errors":[],"errorMessage":null}}
If your JSON is exactly that you have posted, it is unvalid JSON, as per the comments.
The invalid part is the REDACTED words without double-quote.
To bypass this error, you can try in this way:
$data = file_get_contents( $apiurl );
$data = preg_replace( '/:REDACTED(?=\W)/', ':"REDACTED"', $data );
$json = json_decode( $data, True );
This will works on example above, but please note that is a trick, and it can not work if some JSON field has a value like "sometext:REDACTED,sometext": it is improbable, but not impossible.
Actually thank you that site helped a lot realized there was a second array also labeled "data" under the first "data" array so I needed to change it to:
$data['response']['data']['data'] as $dataline
Okay hi guys,
I've been messing with my little side project today (had some great help on something I was stuck on & I've a new little issue I cant seem to get my head around. I'm sure its me just being stupid.
So basically, I've a lot of data from a game (LoL) but I'm not sure how to structure this so it's readable, am I going to have to put it into an array and explode the contents? If so how?
This is what I've got that's pulling the data from an API:
<?php
$summoner_name = 'amphios';
$summoner_id = 21554735;
$profile = new riotapi('euw');
$summonername = $profile->getSummonerByName($summoner_name);
print_r($summonername);
$summonerstats = $profile->getStats($summoner_id, 'ranked');
print_r($summonerstats);
$getsummoner = $profile->getSummoner($summoner_id, 'name');
print_r($getsummoner);
?>
And this is what it's showing (sorry for the big wall of text):
{"id":21554735,"name":"Amphios","profileIconId":588,"summonerLevel":30,"revisionDate":1390725829000}{"summonerId":21554735,"modifyDate":1390725829000,"champions":[{"id":89,"name":"Leona","stats":{"totalSessionsPlayed":1,"totalSessionsLost":1,"totalSessionsWon":0,"totalChampionKills":0,"totalDamageDealt":27547,"totalDamageTaken":21722,"mostChampionKillsPerSession":0,"totalMinionKills":17,"totalDoubleKills":0,"totalTripleKills":0,"totalQuadraKills":0,"totalPentaKills":0,"totalUnrealKills":0,"totalDeathsPerSession":6,"totalGoldEarned":7288,"mostSpellsCast":0,"totalTurretsKilled":0,"totalPhysicalDamageDealt":6559,"totalMagicDamageDealt":20987,"totalFirstBlood":0,"totalAssists":12,"maxChampionsKilled":0,"maxNumDeaths":6}},{"id":254,"name":"Vi","stats":{"totalSessionsPlayed":1,"totalSessionsLost":0,"totalSessionsWon":1,"totalChampionKills":2,"totalDamageDealt":101554,"totalDamageTaken":18470,"mostChampionKillsPerSession":2,"totalMinionKills":122,"totalDoubleKills":0,"totalTripleKills":0,"totalQuadraKills":0,"totalPentaKills":0,"totalUnrealKills":0,"totalDeathsPerSession":1,"totalGoldEarned":11358,"mostSpellsCast":0,"totalTurretsKilled":0,"totalPhysicalDamageDealt":81674,"totalMagicDamageDealt":18995,"totalFirstBlood":0,"totalAssists":15,"maxChampionsKilled":2,"maxNumDeaths":1}},{"id":103,"name":"Ahri","stats":{"totalSessionsPlayed":5,"totalSessionsLost":2,"totalSessionsWon":3,"totalChampionKills":33,"totalDamageDealt":583292,"totalDamageTaken":86957,"mostChampionKillsPerSession":10,"totalMinionKills":798,"totalDoubleKills":2,"totalTripleKills":0,"totalQuadraKills":0,"totalPentaKills":0,"totalUnrealKills":0,"totalDeathsPerSession":22,"totalGoldEarned":55637,"mostSpellsCast":0,"totalTurretsKilled":0,"totalPhysicalDamageDealt":88954,"totalMagicDamageDealt":323163,"totalFirstBlood":0,"totalAssists":38,"maxChampionsKilled":10,"maxNumDeaths":7}},{"id":64,"name":"LeeSin","stats":{"totalSessionsPlayed":2,"totalSessionsLost":0,"totalSessionsWon":2,"totalChampionKills":15,"totalDamageDealt":283794,"totalDamageTaken":47208,"mostChampionKillsPerSession":8,"totalMinionKills":324,"totalDoubleKills":3,"totalTripleKills":1,"totalQuadraKills":0,"totalPentaKills":0,"totalUnrealKills":0,"totalDeathsPerSession":7,"totalGoldEarned":26702,"mostSpellsCast":0,"totalTurretsKilled":2,"totalPhysicalDamageDealt":179409,"totalMagicDamageDealt":102365,"totalFirstBlood":0,"totalAssists":29,"maxChampionsKilled":8,"maxNumDeaths":4}},{"id":81,"name":"Ezreal","stats":{"totalSessionsPlayed":1,"totalSessionsLost":0,"totalSessionsWon":1,"totalChampionKills":10,"totalDamageDealt":168089,"totalDamageTaken":27079,"mostChampionKillsPerSession":10,"totalMinionKills":165,"totalDoubleKills":0,"totalTripleKills":0,"totalQuadraKills":0,"totalPentaKills":0,"totalUnrealKills":0,"totalDeathsPerSession":8,"totalGoldEarned":15275,"mostSpellsCast":0,"totalTurretsKilled":3,"totalPhysicalDamageDealt":131121,"totalMagicDamageDealt":34756,"totalFirstBlood":0,"totalAssists":17,"maxChampionsKilled":10,"maxNumDeaths":8}},{"id":105,"name":"Fizz","stats":{"totalSessionsPlayed":1,"totalSessionsLost":1,"totalSessionsWon":0,"totalChampionKills":3,"totalDamageDealt":80294,"totalDamageTaken":21753,"mostChampionKillsPerSession":3,"totalMinionKills":114,"totalDoubleKills":0,"totalTripleKills":0,"totalQuadraKills":0,"totalPentaKills":0,"totalUnrealKills":0,"totalDeathsPerSession":7,"totalGoldEarned":9389,"mostSpellsCast":0,"totalTurretsKilled":0,"totalPhysicalDamageDealt":19029,"totalMagicDamageDealt":60293,"totalFirstBlood":0,"totalAssists":12,"maxChampionsKilled":3,"maxNumDeaths":7}},{"id":2,"name":"Olaf","stats":{"totalSessionsPlayed":1,"totalSessionsLost":0,"totalSessionsWon":1,"totalChampionKills":5,"totalDamageDealt":183508,"totalDamageTaken":34625,"mostChampionKillsPerSession":5,"totalMinionKills":211,"totalDoubleKills":0,"totalTripleKills":0,"totalQuadraKills":0,"totalPentaKills":0,"totalUnrealKills":0,"totalDeathsPerSession":7,"totalGoldEarned":14095,"mostSpellsCast":0,"totalTurretsKilled":3,"totalPhysicalDamageDealt":117878,"totalMagicDamageDealt":37453,"totalFirstBlood":0,"totalAssists":8,"maxChampionsKilled":5,"maxNumDeaths":7}},{"id":1,"name":"Annie","stats":{"totalSessionsPlayed":6,"totalSessionsLost":2,"totalSessionsWon":4,"totalChampionKills":49,"totalDamageDealt":905226,"totalDamageTaken":122780,"mostChampionKillsPerSession":12,"totalMinionKills":1045,"totalDoubleKills":5,"totalTripleKills":1,"totalQuadraKills":0,"totalPentaKills":0,"totalUnrealKills":0,"totalDeathsPerSession":45,"totalGoldEarned":83361,"mostSpellsCast":0,"totalTurretsKilled":5,"totalPhysicalDamageDealt":84761,"totalMagicDamageDealt":813322,"totalFirstBlood":0,"totalAssists":53,"maxChampionsKilled":12,"maxNumDeaths":12}},{"id":0,"name":"Combined","stats":{"totalSessionsPlayed":18,"totalSessionsLost":6,"totalSessionsWon":12,"totalChampionKills":117,"killingSpree":60,"totalDamageDealt":2333304,"totalDamageTaken":380594,"mostChampionKillsPerSession":12,"totalMinionKills":2796,"totalDoubleKills":10,"totalTripleKills":2,"totalQuadraKills":0,"totalPentaKills":0,"totalUnrealKills":0,"totalDeathsPerSession":103,"totalGoldEarned":223105,"mostSpellsCast":0,"totalTurretsKilled":13,"totalPhysicalDamageDealt":709385,"totalMagicDamageDealt":1411334,"totalNeutralMinionsKilled":234,"totalFirstBlood":0,"totalAssists":184,"totalHeal":26727,"maxLargestKillingSpree":7,"maxLargestCriticalStrike":769,"maxChampionsKilled":12,"maxNumDeaths":12,"maxTimePlayed":3149,"maxTimeSpentLiving":1666,"normalGamesPlayed":0,"rankedSoloGamesPlayed":0,"rankedPremadeGamesPlayed":0,"botGamesPlayed":0}}]}{"summoners":[{"id":21554735,"name":"Amphios"}]}
I'd like to be able to use a lot of this data, and have them in a sort of $api_data['username'] and $api_data['level'] and so on, or a better way.. I'm still getting used to large amounts of data like this.
Use json_decode function for converting your SJON string into PHP array:
$api_data = json_decode($getsummoner);
You could use the PHP json_decode function like this;
$json = '{"id":21554735,"name":"Amphios","profileIconId":588,"summonerLevel":30,"revisionDate":1390725829000}';
$arr = json_decode($json, true);
echo "<xmp>".print_r($arr, true)."</xmp>"; // Display the contents of $arr.
echo "Name is {$arr['name']}"; // Display the contents of $arr['name'].
The above will output the following;
Array
(
[id] => 21554735
[name] => Amphios
[profileIconId] => 588
[summonerLevel] => 30
[revisionDate] => 1390725829000
)
Name is Amphios
I'm trying to access the individual member-fields of a JSON object in PHP from a JSON string but I can't to access the inner-json, all I get is Array.
This is the JSON string
data = (
{
"created_time" = "2018-10-07T04:42:39+0000";
id = 1069496473131329;
name = "NAME_0";
},
{
"created_time" = "2018-09-09T10:31:50+0000";
id = 955684974605664;
name = "NAME_1";
},
At the moment my code is:
$nameString = $_POST["nameData"];
$nameJsonString = json_encode($nameString, JSON_FORCE_OBJECT);
$jsonNameObj = json_decode($nameJsonString, true);
I've been trying to access the individual entry with:
$element = $jsonNameObj['data'][0];
But only receive Array.
Any help would be greatly appreciated,
Cheers :)
After checking the inputted JSON data, I've realised that it doesn't have a consistent form. As opposed to the overall structure being:
JSON -> List -> JSON
Instead, it's:
JSON -> List
The list contains individual elements that can be in a different order. Consequently, calling:
$element = $jsonNameObj['data'][0]['created_time'];
Works sometimes. As there are three-values/object, I can congregate these values into a trio.
I'm sure there's a way to condense this list into a fixed-JSON format but I'm not familiar with how I'd go about that.
At the moment, with a bit of logic on the back-end, I can retrieve the values.
Thanks for your help #Difster and #Osama!