Put a lot of data from an array into usable data? - php
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
Related
How do you unserialize multiple strings of data with a loop?
Problem I have a large csv file that I've exported from a mysql database. One of the file's columns has serialized strings in it. I'm trying to find a way to: Unserialize each string (which lives in its own cell) of the column Output it in a way so the text is in a similar format to this: array ( 'weight' => '108 lbs', 'ah' => '24"', 'sw' => '50"', 'sdw' => '23"', 'shw' => '18"', 'sd' => '27"', 'sh' => '12"', ) Here is a sample of the unserialized rows (there are about 1000 of these): a:7:{s:6:"weight";s:6:"30 lbs";s:2:"ah";s:3:"26"";s:2:"sw";s:3:"20"";s:3:"sdw";s:0:"";s:3:"shw";s:3:"19"";s:2:"sd";s:3:"19"";s:2:"sh";s:3:"17"";} a:7:{s:6:"weight";s:7:"107 lbs";s:2:"ah";s:3:"26"";s:2:"sw";s:3:"72"";s:3:"sdw";s:3:"23"";s:3:"shw";s:3:"18"";s:2:"sd";s:3:"27"";s:2:"sh";s:3:"12"";} a:7:{s:6:"weight";s:6:"37 lbs";s:2:"ah";s:0:"";s:2:"sw";s:0:"";s:3:"sdw";s:0:"";s:3:"shw";s:0:"";s:2:"sd";s:0:"";s:2:"sh";s:0:"";} a:7:{s:6:"weight";s:6:"66 lbs";s:2:"ah";s:3:"26"";s:2:"sw";s:3:"50"";s:3:"sdw";s:3:"23"";s:3:"shw";s:3:"18"";s:2:"sd";s:3:"27"";s:2:"sh";s:3:"12"";} a:7:{s:6:"weight";s:6:"30 lbs";s:2:"ah";s:0:"";s:2:"sw";s:3:"26"";s:3:"sdw";s:0:"";s:3:"shw";s:3:"18"";s:2:"sd";s:3:"39"";s:2:"sh";s:3:"12"";} Questions Is it possible to loop through serialized data, then unserialize it and display it in a desired format (e.g. in a HTML table format)? Note: although this serialized data is from a MySQL database, if possible, I'd prefer not have to hook into the database to retrieve this serialized data again. Attempted Solutions So far, I have: Reviewed the php documentation http://php.net/manual/en/function.unserialize.php Review code examples on Stack Overflow How to use php serialize() and unserialize() How to get each value of unserialized data Used tools like this http://unserialize.onlinephpfunctions.com/ to see how to use this function Tried to implement my own code (see below) After reading up on the topic/issue, I know I likely need to be using: A loop (to loop through the serialized data) var_export or var_dump to display the content in the desired format Code Example Here is the code I used to get the above result: <?php $var1='a:7{s:6:"weight";s:7:"105lbs";s:2:"ah";s:3:"23"";s:2:"sw";s:3:"26"";s:3:"sdw";s:0:"";s:3:"shw";s:3:"17"";s:2:"sd";s:3:"80"";s:2:"sh";s:3:"12"";}'; $var2='a:7:{s:6:"weight";s:7:"108 lbs";s:2:"ah";s:3:"24"";s:2:"sw";s:3:"50"";s:3:"sdw";s:3:"23"";s:3:"shw";s:3:"18"";s:2:"sd";s:3:"27"";s:2:"sh";s:3:"12"";}'; $combined = unserialize($var2); $combined2 = unserialize($var1); print_r($combined); print_r($combined2); ?> Although I'm not getting the desired output, I am able to get some unserialized data to appear on the screen: Array ( [weight] => 108 lbs [ah] => 24" [sw] => 50" [sdw] => 23" [shw] => 18" [sd] => 27" [sh] => 12" ) Array ( [weight] => 105 lbs [ah] => 23" [sw] => 26" [sdw] => [shw] => 17" [sd] => 80" [sh] => 12" ) This is progress but it is problematic since it isn't a loop (was manually inputted) and is lacking HTML markup for easier formatting later on. Any insight on this would be greatly appreciated. Thanks in advance! UPDATE 1 Attempted Solutions I created a temporary CSV file with only one column and 10 rows. See the CSV file here. I've attempted to use the code #geoffry shared, but it doesn't seem to be pulling any info in from my csv file. I was getting an endless loop (1000's of <tr> tags showing up in the console (but with no content from the csv file). After being pointed in the right direction with fgetscsv, I found the code below. With this code, I'm able to get the columns onto the page in their serialized form, so I know for sure the file is being opened properly. But this loop leaves out the unserialize step, which is more important here. <?php $filename = "myfilename.csv"; $id = fopen($filename, "r"); while ($data = fgetcsv($id, filesize($filename))) $table[] = $data; fclose($id); echo "<table>\n"; foreach($table as $row) { echo "<tr>"; foreach($row as $data) echo "<td>$data</td>"; echo "</tr>\n"; } echo "</table>\n"; ?> I've tried combining aspects of this code and #geoffrey 's code below with no luck (for example, adding in the unserialize code to the loop). Questions: I read in the comments of the PHP fgetscsv manual that if you're a mac user (which I am), you need to add auto_detect_line_endings into your code. I've tried this and didn't notice any difference. Could this be part of the problem? The placement of fclose($fp); in both #geoffrey 's code and the one I pasted above are different. Tried using it in different lines/areas of my code/loop without luck. Is this part of the reason why I'm not seeing anything when using unserialized in my code? Anything I might be missing? Thanks again for any insight. Much appreciated! UPDATE 2 I was able to unserialize the serialized data using a helper function called maybe_unserialize. While I wasn't able to loop through all the code, it was a step in the right direction being able to get an unserialized array using PHP. Code Example <?php $original = array( 'a:7:{s:6:"weight";s:7:"149 lbs";s:2:"ah";s:3:"24"";s:2:"sw";s:3:"75"";s:3:"sdw";s:3:"23"";s:3:"shw";s:3:"18"";s:2:"sd";s:3:"27"";s:2:"sh";s:3:"12"";}' ); $string = implode(", ", $original); $done = maybe_unserialize($string); var_export($done); ?> Hopefully this help anyone else with a similar issue!
Since you're dealing with a CSV I will assume that you would want to read in the file and iterate each row where the data you wish to unserialize is in column 5. I am also assuming the HTML output format desired, this should be enought to get you on your way. <table> <?PHP $fp = fopen('file.csv', 'r'); while(($row = fgetcsv($fp)) !== false) { echo "<tr>"; $data = unserialize($row[5]); foreach($data as $name => $value) { echo "<td>" . htmlspecialchars($name ) . "</td>"; echo "<td>" . htmlspecialchars($value) . "</td>"; } echo "</tr>"; } fclose($fp); ?> </table> You may want to check the documentation on fgetcsv as you may need to specify additional arguments depending on your CSV format.
Cannot Parse Paypal "notify_url" Data Into an Associative Array (PHP)
I am setting up a Paypal sandbox. Everything works fine. When the transaction is done, paypal POSTS some data to my "notify_url" page (which I've named process-payment.php). Now, when I post: $array = $_POST; $encodedString = json_decode($array); Now, I can PUT that encoded string in the database, and it looks like: {"mc_gross":"10.00","protection_eligibility":"Eligible", "address_status":"confirmed","payer_id"} Now, my big question is, how can I get THAT (^^^) into an associative array, where I can store those values in a database that records the transaction? Thank you so much for your help in advance! I've already tried: $pp_array = file_get_contents('php://input'); $arrayDump = json_encode($pp_array); $pp_array = json_decode($pp_array, true); Which, obviously, didn't work. So, kinda hoping someone can give me a little tutelage here!
You are trying to use json_decode on an bad array because your payer_id is NULL. Consider filling or removing it. This is a working example with a filled payer_id: $json = '{"mc_gross":"10.00","protection_eligibility":"Eligible", "address_status":"confirmed","payer_id":"2"}'; $json_asoc = (json_decode($json, true)); print $json_asoc['mc_gross']; // 10 For details see here
So, turns out that the code I used to make it work was this: $array = $_POST; $arrayDump = json_encode($array); file_put_contents('payment-record.txt', $arrayDump); $fileContents = file_get_contents('payment-record.txt'); $pp_array = json_decode($fileContents, true); That gave me a workable array. Not sure why I had to write it first, but there you go.
JSON decode multiple nested JSON in PHP
I am using a page builder called King composer for wordpress, where i am trying to build some custom functions, like is intended. My problem is, that the build-in background color picker is base64 encoding the background properties, So i need to decode it - But first i need to decode the 'my-css' json, so that i can access the different properties. this is the return of what i get from the builder. array ( '_id' => '69391', 'image' => '294,9,16', 'gallery-text' => 'Dette er nærmest et galleri', 'my-css' => '{ `kc-css`:{ `any`:{ `typography`{`color|`:`#ffffff`}, `background`{`background|`:`longBase64StringHere`}, `box`:{`margin|`:`100px inherit inherit inherit`} } } }', ) So far i have tried: $decodedBackground = base64_decode($atts['my-css']); which returns as null then i tried : $decodedJson = json_decode($atts['my-css']); which returns : null Also tried some other stuff that went horriably wrong I don't really understand it, I can access the other properties fine, since it is just a part of an array, but the CSS part, I cannot comprehend. I think I need to go deeper in - but I can't get it to work. Been stuck for about 1.5 hours now, so any help or pointers would be appreciated /------ EDIT -----/ So this is how i am trying to inspect the decoded json afterwards - might be important. $decodedJson = json_decode($atts['my-css'], true); echo '<pre>' . var_export($decodedJson, true) . '</pre>';
This is maybe not the best way to do because the JSON in kc-css is not well formated, but this code works for your case: // Refomating JSON $atts['my-css'] = str_replace('`{', '`:{', $atts['my-css']); $atts['my-css'] = str_replace('`', '"', $atts['my-css']); $json = json_decode($atts['my-css'], true);
How to read complex data in array/JSON with PHP?
I've been facing really hard times to read a bunch of data in JSON using json_decode() function in PHP. Basically I need to read basic data to display flights dates origins and destinations. This is how it should be: 20 solutions found. Solution# 1 Sale Price: BRL2919.54 Slice 0 TA 916 GRU 2015-06-16T06:15-03:00 LIM 2015-06-16T09:20-05:00 AV 962 LIM 2015-06-16T10:04-05:00 MIA 2015-06-16T16:48-04:00 And this is the JSON code: http://pastebin.com/dH16RriT When I try to transform that and read it comes with NULL data. $data = json_decode($results, true); // $results is a variable with the JSON content from the URL above echo $data['tripOption']['saleTotal']; // just an example
yes , you should use print_r($a['trips']['tripOption'][0]['saleTotal']) if you want to read the data inside that array,you can do as follows: $data = json_decode($s,true); foreach ($data['trips']['tripOption'] as $item){ print_r($item['saleTotal'] . "\n"); };
I have no problem to decode that data from the json structure you posted. Here is a trivial example script which dumped the decoded array structure: <?php $json = file_get_contents('./data.json'); $data = json_decode($json, true); print_r($data); About the specific data you try and fail to extract: you have to take care to use the correct "path" inside the data structure. This one works: print_r($data['trips']['tripOption']); Since that one is an array yo have to address a specific entry in there to get the output you expect: echo $data['trips']['tripOption'][0]['saleTotal']; // just an example
how to display SimpleXMLElement with php
Hi I have never used xml but need to now, so I am trying to quickly learn but struggling with the structure I think. This is just to display the weather at the top of someones website. I want to display Melbourne weather using this xml link ftp://ftp2.bom.gov.au/anon/gen/fwo/IDV10753.xml Basically I am trying get Melbourne forecast for 3 days (what ever just something that works) there is a forecast-period array [0] to [6] I used this print_r to view the structure: $url = "linkhere"; $xml = simplexml_load_file($url); echo "<pre>"; print_r($xml); and tried this just to get something: $url = "linkhere"; $xml = simplexml_load_file($url); $data = (string) $xml->forecast->area[52]->description; echo $data; Which gave me nothing (expected 'Melbourne'), obviously I need to learn and I am but if someone could help that would be great.
Because description is an attribute of <area>, you need to use $data = (string) $xml->forecast->area[52]['description']; I also wouldn't rely on Melbourne being the 52nd area node (though this is really up to the data maintainers). I'd go by its aac attribute as this appears to be unique, eg $search = $xml->xpath('forecast/area[#aac="VIC_PT042"]'); if (count($search)) { $melbourne = $search[0]; echo $melbourne['description']; }
This is a working example for you: <?php $forecastdata = simplexml_load_file('ftp://ftp2.bom.gov.au/anon/gen/fwo/IDV10753.xml','SimpleXMLElement',LIBXML_NOCDATA); foreach($forecastdata->forecast->area as $singleregion) { $area = $singleregion['description']; $weather = $singleregion->{'forecast-period'}->text; echo $area.': '.$weather.'<hr />'; } ?> You can edit the aforementioned example to extract the tags and attributes you want. Always remember that a good practice to understand the structure of your XML object is printing out its content using, for instance, print_r In the specific case of the XML you proposed, cities are specified through attributes (description). For this reason you have to read also those attributes using ['attribute name'] (see here for more information). Notice also that the tag {'forecast-period'} is wrapped in curly brackets cause it contains a hyphen, and otherwise it wouldn generate an error.