Illegal String Offset in Multidimensional Array - php

I am attempting to fetch a JSON file from a separate website, read that file and then decode it into a multidimensional array. So far at that point it seems to work. However, when I try and break it all down into variables to echo, it goes wrong when its 4 levels deep. You can see the actual JSON file from the link in the PHP code and below is the PHP Code I am using. The specific variables that have problems are $prices in 2 areas and $rulings. Any help someone can provide with this would be appreciated.
<?php
$path = 'https://www.mtgjson.com/json/LEA.json';
$FileContents = file_get_contents($path);
$cards = json_decode($FileContents, true);
foreach ($cards['cards'] as $mtgcard){
$Artist = $mtgcard['artist'];
$borderColor = $mtgcard['borderColor'];
$colorIdentity = $mtgcard['colorIdentity'][0];
$Colors = $mtgcard['colors'][0];
$convertedManaCost = $mtgcard['convertedManaCost'];
$edhrecRank = $mtgcard['edhrecRank'];
$flavorText = $mtgcard['flavorText'];
$cards_foreignData = implode($mtgcard['foreignData'],",");
$foreignData = explode(',', $cards_foreignData);
$frameVersion = $mtgcard['frameVersion'];
$hasFoil = $mtgcard['hasFoil'];
$hasNonFoil = $mtgcard['hasNonFoil'];
$isPaper = $mtgcard['isPaper'];
$Layout = $mtgcard['layout'];
$cards_legalities = implode($mtgcard['legalities'],",");
$legalities = explode(',', $cards_legalities);
$manaCost = $mtgcard['manaCost'];
$mcmId = $mtgcard['mcmId'];
$mcmMetaId = $mtgcard['mcmMetaId'];
$mtgstocksId = $mtgcard['mtgstocksId'];
$multiverseId = $mtgcard['multiverseId'];
$name = $mtgcard['name'];
$number = $mtgcard['number'];
$originalText = $mtgcard['originalText'];
$originalType = $mtgcard['originalType'];
$power = $mtgcard['power'];
$cards_prices = implode($mtgcard['prices'],",");
$prices = explode(',', $cards_prices);
$cards_prices_2 = implode($cards_prices['paper'],",");
$prices_2 = explode(',', $cards_prices_2);
$cards_printings = implode($mtgcard['printings'],",");
$printings = explode(',', $cards_printings);
$cards_purchaseUrls = implode($mtgcard['purchaseUrls'],",");
$purchaseUrls = explode(',', $cards_purchaseUrls);
$rarity = $mtgcard['rarity'];
$cards_rulings = implode($mtgcard['rulings'],",");
$rulings = explode(',', $cards_rulings);
$scryfallId = $mtgcard['scryfallId'];
$scryfallIllustrationId = $mtgcard['scryfallIllustrationId'];
$scryfallOracleId = $mtgcard['scryfallOracleId'];
$cards_subtypes = implode($mtgcard['subtypes'],",");
$subtypes = explode(',', $cards_subtypes);
$cards_supertypes = implode($mtgcard['supertypes'],",");
$supertypes = explode(',', $cards_supertypes);
$tcgplayerProductId = $mtgcard['tcgplayerProductId'];
$text = $mtgcard['text'];
$toughness = $mtgcard['toughness'];
$type = $mtgcard['type'];
$types = $mtgcard['types'][0];
$uuid = $mtgcard['uuid'];
$a = substr($scryfallId, 0, 1);
$b = substr($scryfallId, 1, 1);
$convert = "<img src='https://img.scryfall.com/cards/large/front/" .$a. "/" .$b. "/" .$scryfallId. ".jpg' />";
echo $convert;
echo "Artist Name: " .$Artist. "<br/>";
echo "Border Color: " .$borderColor. "<br/>";
echo "colorIdentity: " .$colorIdentity. "<br/>";
echo "Colors: " .$Colors. "<br/>";
echo "convertedManaCost: " .$convertedManaCost. "<br/>";
echo "edhrecRank: " .$edhrecRank. "<br/>";
echo "flavorText: " .$flavorText. "<br/>";
echo "foreignData: " .$foreignData[0]. "<br/>";
echo "frameVersion: " .$frameVersion. "<br/>";
echo "hasFoil: " .$hasFoil. "<br/>";
echo "hasNonFoil: " .$hasNonFoil. "<br/>";
echo "isPaper: " .$isPaper. "<br/>";
echo "Layout: " .$Layout. "<br/>";
echo "Brawl: " .$legalities[0]. "<br/>";
echo "Commander: " .$legalities[1]. "<br/>";
echo "Duel: " .$legalities[2]. "<br/>";
echo "Future: " .$legalities[3]. "<br/>";
echo "Historic: " .$legalities[4]. "<br/>";
echo "Legacy: " .$legalities[5]. "<br/>";
echo "Modern: " .$legalities[6]. "<br/>";
echo "Oldschool: " .$legalities[7]. "<br/>";
echo "Penny: " .$legalities[8]. "<br/>";
echo "Pioneer: " .$legalities[9]. "<br/>";
echo "Standard: " .$legalities[10]. "<br/>";
echo "Vintage: " .$legalities[11]. "<br/>";
echo "Manacost: " .$manaCost. "<br/>";
echo "mcmId: " .$mcmId. "<br/>";
echo "mcmMetaId: " .$mcmMetaId. "<br/>";
echo "mtgstocksId: " .$mtgstocksId. "<br/>";
echo "multiverseId: " .$multiverseId. "<br/>";
echo "name: " .$name. "<br/>";
echo "number: " .$number. "<br/>";
echo "originaltext: " .$originalText. "<br/>";
echo "originaltype: " .$originalType. "<br/>";
echo "power: " .$power. "<br/>";
echo "MTGO prices: " .$prices[0]. "<br/>";
echo "MTGO Foil Prices: " .$prices[1]. "<br/>";
echo "Paper Prices: " .prices[2] "<br/>"; <- 4 levels deep doesnt work
echo "Paper Foil Prices: " .$prices[3]. "<br/>"; <- 4 levels deep doesnt work
echo "purchaseUrls: " .$purchaseUrls[0]. "<br/>";
echo "purchaseUrls: " .$purchaseUrls[1]. "<br/>";
echo "purchaseUrls: " .$purchaseUrls[2]. "<br/>";
echo "rarity: " .$rarity. "<br/>";
echo "ruling: " .$rulings['date'].$rulings['text'] "<br/>"; <-- 4 levels deep doesnt work
echo "scryfallId: " .$scryfallId. "<br/>";
echo "scryfallIllustrationId: " .$scryfallIllustrationId. "<br/>";
echo "scryfallOracleId: " .$scryfallOracleId. "<br/>";
echo "subtypes: " .$subtypes[0]. "<br/>";
echo "supertypes: " .$supertypes[0]. "<br/>";
echo "tcgplayerProductId: " .$tcgplayerProductId. "<br/>";
echo "text: " .$text. "<br/>";
echo "toughness: " .$toughness. "<br/>";
echo "type: " .$type. "<br/>";
echo "types: " .$types. "<br/>";
echo "uuid: " .$uuid. "<br/>";
}
?>

You should mention the array name to fetch the content inside array, here is the example code and artist is with small "a" not capital
Edit as per comment request
Get the array of 'legalities' a string with , separated using implode and than explode with , and convert into an array to print those
Note: only the values will be imported using implode not the keys
<?php
// error_reporting(0);
// header('Content-type: application/json');
$path = 'https://www.mtgjson.com/json/LEA.json';
$FileContents = file_get_contents($path);
$cards = json_decode($FileContents, true);
foreach($cards['cards'] as $mtgcard) {
echo '<br>' .$course_data1 = $mtgcard['artist'];
$cards_legalities = implode($mtgcard['legalities'],",");
$myArray = explode(',', $cards_legalities);
echo $myArray[0];// 1st array
//Multidimensional Array for your updated question
$cards_prices_paper = implode($mtgcard['prices']['paper'],",");
$prices_paper_array = explode(',', $cards_prices_paper);
echo $prices_paper_array[0];
$rulings_date = implode(', ', array_column($mtgcard['rulings'], 'date'));
$rulings_date_array = explode(",", $rulings_date);
echo $rulings_date_array[0];
}
?>

Related

Reading Line by Line Using PHP Via JSON String

I am trying to create a PHP function which will allow me to read selected lines from a text file using a JSON string. The JSON string consists of two numbers separated by a comma. The first number is the line I want to seek, and the second is the number of lines to read going downward.
For example, I have this sentence in a separate text file:
A diving spiral attack in which Pikachu head butts downward while
being surrounded by electricity.
(If you're wondering, this is part of my upcoming fan site, still under construction).
The sentence starts at line 6, and uses up 2 lines. So in my JSON file, I would write "6,2". The explode() command is ran using the comma as the delimiter, allowing me to store these number into two individual variables, $start and $length.
$result = explode(",", $sample); // In JSON string, $sample is $i["desc"]
$start = $result[0];
$length = $result[1];
With the variables now in place, the following lines will then be called to perform the actual line-by-line extraction.
$file = new SplFileObject("pikachu/pikachu.txt");
for ($i = $start; $i <= ($start+$length); $i++) {
$file->seek($i-1);
echo "$file";
}
I did a test of my script using a direct call instead of through JSON parsing. That worked. But when I tried to use the JSON string, I ended up with both a Runtime and a Fatal Error.
How do I fix the scripts so that I can use the JSON string as markers for seeking lines from an external text to print while avoiding the Runtime and Fatal Errors?
(EDIT: The problem became too difficult for me to fix, so I've decided to ditch the line-by-line seek feature for now. I will revisit this on a later date. I will leave the code below for archival purposes.)
character.php
<?php
$name = $_GET['name'];
// Step 1: Get the name from the previous page and store it.
$file = file_get_contents("characters/$name/$name.json");
// Step 2: Use the name to find a JSON file for the character (We'll do the moves list later).
$json = json_decode($file, true);
// Step 3: Decode the JSON file
$character = $json["character"][0]["name"];
$group = $json["character"][0]["group"];
$series = $json["character"][0]["series"];
$story = $json["character"][0]["story"];
$snapback = $json["character"][0]["snapback"];
$interrupt = $json["character"][0]["interrupt"];
$hiddenpow = $json["character"][0]["hiddenpow"];
$disrupt = $json["character"][0]["disrupt"];
$assist1 = $json["character"][0]["assist1"];
$assist2 = $json["character"][0]["assist2"];
$assist3 = $json["character"][0]["assist3"];
$counter = $json["character"][0]["counter"];
$bros = $json["character"][0]["bros"];
$party = $json["character"][0]["party"];
$ground = $json["character"][0]["ground"];
$jump = $json["character"][0]["jump"];
$superjump = $json["character"][0]["superjump"];
$launcher = $json["character"][0]["launcher"];
$altlaunch = $json["character"][0]["altlaunch"];
$acfinisher = $json["character"][0]["acfinisher"];
// Step 4: Retrieve variables and store them for use
echo "<HTML>\n";
echo "<HEAD>\n";
echo "<TITLE>Marvel & Capcom vs. Pokemon: $character</TITLE>\n\n";
echo "<LINK rel=\"stylesheet\" type=\"text/css\" href=\"http://fonts.googleapis.com/css?family=Roboto\">\n";
echo "<LINK rel=\"stylesheet\" type=\"text/css\" href=\"http://fonts.googleapis.com/css?family=Open+Sans\">\n";
echo "<LINK rel=\"stylesheet\" type=\"text/css\" href=\"media/style.css\">\n";
echo "<SCRIPT type=\"text/javascript\" src=\"media/tabs.js\"></SCRIPT>\n";
echo "<SCRIPT type=\"text/javascript\">\n";
echo "function toggle_visibility(id) {\n";
echo " var movename = id.nextSibling.nextSibling;\n";
echo " if(movename.style.display == \"block\")\n";
echo " movename.style.display = \"none\";\n";
echo " else\n";
echo " movename.style.display = \"block\";\n";
echo "}\n";
echo "</SCRIPT>";
echo "</HEAD>\n\n";
echo "<BODY onload=\"init()\">\n\n";
// Step 5: The HTML stuff begins
echo "<TABLE id=\"Character\">\n";
echo " <TR>\n";
echo " <TD class=\"Name\">" . strtoupper($character) . "</TD>\n";
echo " <TD class=\"Image\" rowspan=\"4\"><IMG src=\"characters/$name/$name.jpg\"></TD></TR>\n";
echo " <TR>\n";
echo " <TD class=\"Series\">Series: $series</TD></TR>\n";
echo " <TR>\n";
echo " <TD class=\"Story\">$story</TD></TR>\n";
// Step 6: Write the variables to the file
echo " <TR>\n";
echo " <TD style=\"vertical-align: top\">\n";
echo " <TABLE id=\"$group\">\n";
function moverw ($move) {
$subfollow = "FOLLOW>>";
$follow = "FOLLOW>";
if (strpos($move,$subfollow) !== false)
$move .= " (followup)";
else if (strpos($move,$follow) !== false)
$move .= " (followup)";
$move = str_replace("FOLLOW>>", "<IMG class=\"Followup\" src=\"images/follow.png\" style=\"text-indent: 5px\"> ", $move);
$move = str_replace("FOLLOW>", "<IMG class=\"Followup\" src=\"images/follow.png\"> ", $move);
return ($move);
}
function descrw ($desc,$name) {
$result = explode(",", $desc);
$start = $result[0];
$length = $result[1];
$file = new SplFileObject("characters/$name/$name.txt");
$result = "";
for ($i = $start; $i <= ($start+$length); $i++) {
$file->seek($i-1);
$result .= $file;
}
return($result);
}
function commrw ($command) {
$command = str_replace("AM,", "<IMG title=\"Assist Mode\" src=\"images/assist.gif\"> ", $command);
$command = str_replace("SM,", "<IMG title=\"Single Mode\" src=\"images/single.gif\"> ", $command);
$command = str_replace("BRAWL,", "<IMG title=\"Super Smash Brawl\" src=\"images/brawl.png\"> ", $command);
$command = str_replace("uf,", "<IMG class=\"Arrow\" src=\"images/uf.png\">", $command);
$command = str_replace("df,", "<IMG class=\"Arrow\" src=\"images/df.png\">", $command);
$command = str_replace("ub,", "<IMG class=\"Arrow\" src=\"images/ub.png\">", $command);
$command = str_replace("db,", "<IMG class=\"Arrow\" src=\"images/db.png\">", $command);
$command = str_replace("u,", "<IMG class=\"Arrow\" src=\"images/u.png\">", $command);
$command = str_replace("f,", "<IMG class=\"Arrow\" src=\"images/f.png\">", $command);
$command = str_replace("d,", "<IMG class=\"Arrow\" src=\"images/d.png\">", $command);
$command = str_replace("b,", "<IMG class=\"Arrow\" src=\"images/b.png\">", $command);
$command = str_replace("+", "<IMG class=\"Plus\" src=\"images/plus.png\">", $command);
$command = str_replace("AP", "<IMG class=\"Button\" src=\"images/punch.png\">", $command);
$command = str_replace("AK", "<IMG class=\"Button\" src=\"images/kick.png\">", $command);
$command = str_replace("A1", "<IMG class=\"Button\" title=\"Assist 1\" src=\"images/assist1.png\">", $command);
$command = str_replace("A2", "<IMG class=\"Button\" title=\"Assist 2\" src=\"images/assist2.png\">", $command);
$command = str_replace("AB", "<IMG class=\"Button\" title=\"Assist\" src=\"images/assist.png\">", $command);
$command = str_replace("LP", "<IMG class=\"Button\" title=\"Jab\" src=\"images/jab.png\">", $command);
$command = str_replace("LK", "<IMG class=\"Button\" title=\"Short\" src=\"images/short.png\">", $command);
$command = str_replace("MP", "<IMG class=\"Button\" title=\"Strong\" src=\"images/strong.png\">", $command);
$command = str_replace("MK", "<IMG class=\"Button\" title=\"Forward\" src=\"images/forward.png\">", $command);
$command = str_replace("HP", "<IMG class=\"Button\" title=\"Fierce\" src=\"images/fierce.png\">", $command);
$command = str_replace("HK", "<IMG class=\"Button\" title=\"Roundhouse\" src=\"images/roundhouse.png\">", $command);
$command = str_replace("FOLLOW>>", "<IMG class=\"Followup\" src=\"images/follow.png\" style=\"text-indent: 5px\"> ", $command);
$command = str_replace("FOLLOW>", "<IMG class=\"Followup\" src=\"images/follow.png\"> ", $command);
$command = str_replace("degrees", "°", $command);
return ($command);
}
function typerw ($type) {
$type = str_replace("BUG.", "<IMG src=\"images/bug.png\">", $type);
$type = str_replace("CYBER.", "<IMG src=\"images/cyber.png\">", $type);
$type = str_replace("DARK.", "<IMG src=\"images/dark.png\">", $type);
$type = str_replace("DRAGON.", "<IMG src=\"images/dragon.png\">", $type);
$type = str_replace("ELECTRIC.", "<IMG src=\"images/electric.png\">", $type);
$type = str_replace("FAIRY.", "<IMG src=\"images/fairy.png\">", $type);
$type = str_replace("FIGHTING.", "<IMG src=\"images/fighting.png\">", $type);
$type = str_replace("FIRE.", "<IMG src=\"images/fire.png\">", $type);
$type = str_replace("FLYING.", "<IMG src=\"images/flying.png\">", $type);
$type = str_replace("GHOST.", "<IMG src=\"images/ghost.png\">", $type);
$type = str_replace("GRASS.", "<IMG src=\"images/grass.png\">", $type);
$type = str_replace("GROUND.", "<IMG src=\"images/ground.png\">", $type);
$type = str_replace("ICE.", "<IMG src=\"images/ice.png\">", $type);
$type = str_replace("LIGHT.", "<IMG src=\"images/light.png\">", $type);
$type = str_replace("NORMAL.", "<IMG src=\"images/normal.png\">", $type);
$type = str_replace("PSYCHIC.", "<IMG src=\"images/psychic.png\">", $type);
$type = str_replace("STEEL.", "<IMG src=\"images/steel.png\">", $type);
$type = str_replace("WATER.", "<IMG src=\"images/water.png\">", $type);
return ($type);
}
function noterw ($note) {
$note = str_replace(".AM.", "<IMG title=\"Assist Mode\" src=\"images/assist.gif\"> ", $note);
$note = str_replace(".SM.", "<IMG title=\"Single Mode\" src=\"images/single.gif\"> ", $note);
$note = str_replace(".HP.", "<IMG class=\"HiddenPower\" title=\"Hidden Power\"src=\"images/hiddenpower.png\">", $note);
return ($note);
}
foreach ($json["character"][0]["moves"] as $i) {
if ($i["flag"] == "normal") {
$move = strtoupper($i["move"]);
$desc = $i["desc"];
$command = $i["comm"];
$type = $i["type"];
$note = $i["note"];
echo " <TR>\n";
echo " <TD class=\"MoveName Normal\">" . moverw($move) . "\n";
echo " <DIV class=\"Details\">" . descrw($desc,$name) . "</DIV></TD>\n";
echo " <TD class=\"Command\">" . commrw($command) . "</TD>\n";
echo " <TD class=\"Type\">" . typerw($type) . "</TD>\n";
echo " <TD class=\"Note\">" . noterw($note) . "</TD></TR>\n";
}
if ($i["flag"] == "special") {
$move = strtoupper($i["move"]);
$command = $i["comm"];
$type = $i["type"];
$note = $i["note"];
echo " <TR>\n";
echo " <TD class=\"MoveName Special\">" . moverw($move) . "\n";
echo " <DIV class=\"Details\">" . $i["desc"] . "</DIV></TD>\n";
echo " <TD class=\"Command\">" . commrw($command) . "</TD>\n";
echo " <TD class=\"Type\">" . typerw($type) . "</TD>\n";
echo " <TD class=\"Note\">" . noterw($note) . "</TD></TR>\n";
}
if ($i["flag"] == "hyper") {
$move = strtoupper($i["move"]);
$command = $i["comm"];
$type = $i["type"];
$note = $i["note"];
echo " <TR>\n";
echo " <TD class=\"MoveName Hyper\">" . moverw($move) . "\n";
echo " <DIV class=\"Details\">" . $i["desc"] . "</DIV></TD>\n";
echo " <TD class=\"Command\">" . commrw($command) . "</TD>\n";
echo " <TD class=\"Type\">" . typerw($type) . "</TD>\n";
echo " <TD class=\"Note\">" . noterw($note) . "</TD></TR>\n";
}
if ($i["flag"] == "final") {
$move = strtoupper($i["move"]);
$command = $i["comm"];
$type = $i["type"];
$note = $i["note"];
echo " <TR>\n";
echo " <TD class=\"MoveName Final\">" . moverw($move) . "\n";
echo " <DIV id=\"Final\" class=\"Details\">" . $i["desc"] . "</DIV></TD>\n";
echo " <TD class=\"Command\">" . commrw($command) . "</TD>\n";
echo " <TD class=\"Type\">" . typerw($type) . "</TD>\n";
echo " <TD class=\"Note\">" . noterw($note) . "</TD></TR>\n";
}
}
// Step 7: Write the moves. When Command and Type are parsed, execute respective rewriters. Saves me from typing lots, hun ;)
echo " </TABLE></TD></TR>\n";
echo " <TR>\n";
echo " <TD colspan=\"2\">\n";
echo " <UL id=\"tabs\">\n";
echo " <LI>SINGLE MODE</LI>\n";
echo " <LI>ASSIST MODE</LI>\n";
echo " <LI>COMBO PROFILE</LI>\n";
echo " <LI>ATTACK PROFILE</LI></UL>\n";
echo " <DIV class=\"tabContent\" id=\"Single\">\n";
echo " <TABLE id=\"Single\" border=1>\n";
echo " <TR>\n";
echo " <TH>Snapback:</TH>\n";
echo " <TD>$snapback</TD></TR>\n";
echo " <TR>\n";
echo " <TH>Interrupt:</TH>\n";
echo " <TD>$interrupt</TD></TR>\n";
echo " <TR>\n";
echo " <TH>Hidden Power:</TH>\n";
echo " <TD>$hiddenpow</TD></TR>\n";
echo " <TR>\n";
echo " <TH class=\"Header Rumble\"colspan=\"2\">RUMBLE CHART</TH></TR>\n";
echo " <TR>\n";
echo " <TD colspan=\"2\"></TH></TR></TABLE></DIV>\n";
echo " <DIV class=\"tabContent\" id=\"Assist\">\n";
echo " <TABLE id=\"Assist\" border=1>\n";
echo " <TR>\n";
echo " <TH>Disrupt:</TH>\n";
echo " <TD>$disrupt</TD></TR>\n";
echo " <TR>\n";
echo " <TH colspan=2>Assist Attacks</TH></TR>\n";
echo " <TR>\n";
echo " <TH><IMG class=\"Button\" title=\"Assist\" src=\"images/assist.png\"></TH>\n";
echo " <TD>$assist1</TD></TR>\n";
echo " <TR>\n";
echo " <TH><IMG class=\"Button\" title=\"Assist\" src=\"images/assist.png\"><IMG class=\"Plus\" src=\"images/plus.png\"><IMG class=\"Button\" title=\"Fierce\" src=\"images/fierce.png\"></TH>\n";
echo " <TD>$assist2</TD></TR>\n";
echo " <TR>\n";
echo " <TH><IMG class=\"Button\" title=\"Assist\" src=\"images/assist.png\"><IMG class=\"Plus\" src=\"images/plus.png\"><IMG class=\"Button\" title=\"Roundhouse\" src=\"images/roundhouse.png\"></TH>\n";
echo " <TD>$assist3</TD></TR>\n";
echo " <TR>\n";
echo " <TH>Cross-Over Counter:</TH>\n";
echo " <TD>$counter</TD></TR>\n";
echo " <TR>\n";
echo " <TH colspan=2>Super Smash Melee</TH></TR>\n";
echo " <TR>\n";
echo " <TH>Bros. Attack:</TH>\n";
echo " <TD>$bros</TD></TR>\n";
echo " <TR>\n";
echo " <TH>Party Attack:</TH>\n";
echo " <TD>$party</TD></TR></TABLE></DIV>\n";
echo " <DIV class=\"tabContent\" id=\"Combo\">\n";
echo " <TABLE id=\"Combo\" border=1>\n";
echo " <TR>\n";
echo " <TH colspan=2>???</TH></TR>\n";
echo " <TR>\n";
echo " <TH>Ground:</TH>\n";
echo " <TD>$ground</TD></TR>\n";
echo " <TR>\n";
echo " <TH>Jump:</TH>\n";
echo " <TD>$jump</TD></TR>\n";
echo " <TR>\n";
echo " <TH>Super Jump:</TH>\n";
echo " <TD>$superjump</TD></TR>\n";
echo " <TR>\n";
echo " <TH colspan=2></TH></TR>\n";
echo " <TR>\n";
echo " <TH>Launcher:</TH>\n";
echo " <TD>$launcher</TD></TR>\n";
if ($altlaunch != null) {
echo " <TR>\n";
echo " <TH>Alternate Launch:</TH>\n";
echo " <TD>$altlaunch</TD></TR>\n";
}
echo " <TR>\n";
echo " <TH>AC Finishers:</TH>\n";
echo " <TD>$acfinisher</TD></TR></TABLE></DIV>\n";
echo " <DIV class=\"tabContent\" id=\"Attack\">\n";
echo " $test 4\n";
echo " </DIV>\n";
echo " </TD></TR></TABLE></TD></TR></TABLE>\n\n";
echo "</BODY></HTML>";
?>
$name.json, where $name is the name of the character (using pikachu as demo):
{"character":[
{
"name":"Pikachu",
"group":"Pokemon",
"series":"Pokemon",
"story":"To-do...",
"moves":[
{
"flag":"normal",
"move":"Discharge",
"desc":"3,2",
"comm":"Press HP (crouch) (air)",
"type":"ELECTRIC.",
"note":"Notes"
},
{
"flag":"normal",
"move":"Electric Screw",
"desc":"6,2",
"comm":"Tilt d,+HP [air]",
"type":"ELECTRIC.",
"note":"Notes"
},
{
"flag":"normal",
"move":"Tackle",
"desc":"9,1",
"comm":"Tap f, , f,",
"type":"NORMAL.",
"note":"Notes"
},
{
"flag":"special",
"move":"Quick Attack",
"desc":"11,2",
"comm":"Tap any direction and Press AP (air)",
"type":"ELECTRIC.FIGHTING.",
"note":"Notes"
},
{
"flag":"special",
"move":"Thunder Jolt",
"desc":"14",
"comm":"Motion d,df,f,+AP",
"type":"ELECTRIC.",
"note":"Notes"
},
{
"flag":"special",
"move":"Electro Ball",
"desc":"16,2",
"comm":"Motion d,df,f,+AP [air]",
"type":"ELECTRIC.",
"note":"Notes"
},
{
"flag":"special",
"move":"Thunder",
"desc":"19,2",
"comm":"Motion f,d,df,+AP (air)",
"type":"ELECTRIC.",
"note":"Notes"
},
{
"flag":"special",
"move":"Electric Chair",
"desc":"22,2",
"comm":"Motion f,df,d,db,b,+AP",
"type":"ELECTRIC.",
"note":"Notes"
},
{
"flag":"hyper",
"move":"Thunder Shock",
"desc":"25,2",
"comm":"Motion d,df,f,+APAP (air)",
"type":"ELECTRIC.",
"note":"Notes"
},
{
"flag":"hyper",
"move":"Thunder Bolt",
"desc":"28,1",
"comm":"Motion d,df,f,+AKAK (air)",
"type":"ELECTRIC.",
"note":"Notes"
},
{
"flag":"hyper",
"move":"Skull Bash",
"desc":"30,2",
"comm":"Motion d,db,b,+APAP (air)",
"type":"ELECTRIC.FIGHTING.",
"note":"Notes"
},
{
"flag":"final",
"move":"Volt Tackle",
"desc":"33,2",
"comm":"Motion d,df,f,d,df,f,+APAP (air)",
"type":"ELECTRIC.",
"note":"Notes"
}],
"snapback":"Crouching Forward",
"interrupt":"Thunder Jolt, Thunder",
"hiddenpow":"Hidden Power Enhancements (Line per line lookup)",
"disrupt":"Thunder",
"assist1":"Thunder Jolt",
"assist2":"Thunder",
"assist3":"Quick Attack",
"counter":"Thunder",
"bros":"Skull Bash",
"party":"Thunder Bolt",
"ground":"Punch to Kick",
"jump":"Punch to Kick",
"superjump":"Zig Zag",
"launcher":"Standing Roundhouse",
"altlaunch":"Crouching Strong",
"acfinisher":"Discharge, Electric Screw, Quick Attack, Electro Ball, Thunder, Thunder Shock, Thunder Bolt, Skull Bash"
}
]}
The problem is in this function, and has nothing to do with your use of JSON. It's just a simple variable scope issue.
function descrw ($desc) {
$result = explode(",", $desc);
$start = $result[0];
$length = $result[1];
$file = new SplFileObject("$name/$name.txt");
for ($i = $start; $i <= ($start+$length); $i++) {
$file->seek($i-1);
echo "$file";
}
return(0);
}
The variable $name is not defined, so it's trying to open the file /.txt. You need to change the function so it takes $name as an argument. And since the caller of descrw expects it to return a string so that it can be concatenated, descrw shouldn't do its own echo.
function descrw ($desc, $name) {
$result = explode(",", $desc);
$start = $result[0];
$length = $result[1];
$file = new SplFileObject("$name/$name.txt");
$result = '';
for ($i = $start; $i <= ($start+$length); $i++) {
$file->seek($i-1);
$result .= $file;
}
return($result);
}
Then change the place where it's called to pass the argument:
echo " <DIV class=\"Details\">" . descrw($desc, $name) . "</DIV></TD>\n";

How to pass all the values in an array which is processed by for loop?

<?php
$xml = simplexml_load_file("sample.xml");
echo " ". $xml->getName() . "<br />";
foreach($xml->children()->children() as $child)
{
$a=$child->getName() . "<br />";
array_push($a);
echo $a;
}
?>
Try this
<?php
$arr = array();
$xml = simplexml_load_file("sample.xml");
echo " ". $xml->getName() . "<br />";
foreach($xml->children()->children() as $child)
{
$a=$child->getName() . "<br />";
$arr[] = $a;
echo $a;
}
?>

php json not showing Wunderground station list

I'm trying to show a list of all nearby weather stations.
I have the code:
$json_string = file_get_contents("http://api.wunderground.com/api/8b19ccf6a06c0826/geolookup/conditions/q/Netherlands/Rotterdam.json");
$parsed_json = json_decode($json_string);
$stations = $parsed_json->{'location'}->{'nearby_weather_stations'}->{'pws'}->{'station'};
$count = count($stations);
for($i = 0; $i < $count; $i++)
{
$station = $stations[$i];
if (count($station) > 1)
{
echo "City: " . $station->{'city'} . "\n";
echo "State: " . $station->{'state'} . "\n";
echo "Latitude: " . $station->{'lat'} . "\n";
echo "Longitude: " . $station->{'lon'} . "\n";
}
}
But currently it's not showing anything, i have searched for examples but i couldn't find any solution fot this problem.
Alternatively, you could use a simple foreach to iterate those values. Consider this example:
$json_string = file_get_contents("http://api.wunderground.com/api/8b19ccf6a06c0826/geolookup/conditions/q/Netherlands/Rotterdam.json");
$parsed_json = json_decode($json_string, true); // <-- second parameter to TRUE to use it as an array
$desired_values = $parsed_json['location']['nearby_weather_stations']['pws']['station'];
foreach($desired_values as $key => $value) {
echo "<hr/>";
echo "City: " . $value['city'] . "<br/>";
echo "State: " . $value['state'] . "<br/>";
echo "Latitude: " . $value['lat'] . "<br/>";
echo "Longitude: " . $value['lon'] . "<br/>";
echo "<hr/>";
}
Sample Fiddle

PHP For Each Loop? There has to be a better way

<?php
header("Content-type: text/plain");
$GLOBALS["db_name"] = "fggff_highscores";
$GLOBALS["table_name"] = "testing";
$GLOBALS["view_user"] = "fgfggg_players";
$GLOBALS["view_pass"] = "removed";
$username = strip_tags($_GET["player"]);
$fileContents = #file_get_contents("http://hiscore.runescape.com/index_lite.ws?player=" . $username);
echo $fileContents;
if ($fileContents == FALSE) {
die("PLAYER NOT FOUND");
}
//$content = array();
$data = explode("\n", $fileContents);
/*
foreach ($data as $word) {
$index = $skills[$index];
$new_data = explode (",", $word);
$content[$index]["rank"] = $new_data[0];
$content[$index]["level"] = $new_data[1];
$content[$index]["experience"] = $new_data[2];
$index++;
}
*/
$stats0 = explode(",", $data[0]);
echo "\n";
echo "\n";
echo "Overall Rank: " .number_format($stats0[0]);
echo "\n";
echo "Total Level: " .number_format($stats0[1]);
echo "\n";
echo "Overall Total XP: " .number_format($stats0[2]);
$stats1 = explode(",", $data[1]);
echo "\n";
echo "\n";
echo "Attack Rank: " .number_format($stats1[0]);
echo "\n";
echo "Attack Level: " .number_format($stats1[1]);
echo "\n";
echo "Attack XP: " .number_format($stats1[2]);
$stats2 = explode(",", $data[2]);
echo "\n";
echo "\n";
echo "Defence Rank: " .number_format($stats2[0]);
echo "\n";
echo "Defence Level: " .number_format($stats2[1]);
echo "\n";
echo "Defence XP: " .number_format($stats2[2]);
?>
Example above should be working when ran you can use this player to see output -- .php?player=zezima
The output of each $data[0] is something like--------53,2496,1661657944
53-----------------------number_format($stats0[0])
2,496--------------------number_format($stats0[1])
1,661,657,944------------number_format($stats0[2])
--
Then I'm trying to break up each $data[] index into 3 pieces, the way I have it above works but I want to be able to do something like a for each loop to go through each $data[] indexes and break each up using explode(",", $data[0]); explode(",", $data[1]); explode(",", $data[2]); but it would have the index increment each time. What I need in the end is each value to be in a variable that I can use. Example:
$apple = number_format($stats0[0]);
echo $apple;
This is what I've tried something with:
$content = array();
foreach ($data as $word) {
$index = $skills[$index];
$new_data = explode (",", $word);
$content[$index]["rank"] = $new_data[0];
$content[$index]["level"] = $new_data[1];
$content[$index]["experience"] = $new_data[2];
$index++;
}
instead of repeating yourself again and again, create a function like this one:
function print($data, $i){
$stats0 = explode(",", $data[$i]);
echo "\n\nOverall Rank: " .number_format($stats0[0]) . "\n";
echo "Total Level: " .number_format($stats0[1]) . "\n";
echo "Overall Total XP: " .number_format($stats0[2]);
}
and call it in a loop.

PHP function, returning (in Windows) Rx and Tx for each adapter?

This is supposed to return raw values for Rx and Tx for each adapter (output is in pairs) ONLY of the adapter has transferred more than zero data.
<?php
//windows network usage testing
function win_netinfo(){
ob_start();
$wmi = new COM("Winmgmts://");
$nets = $wmi->execquery("SELECT * FROM Win32_PerfRawData_Tcpip_NetworkInterface WHERE BytesSentPersec > 1");
foreach ($nets as $net)
{
$net_txbytes = $net->BytesSentPersec;
$net_rxbytes = $net->BytesReceivedPersec;
if ($net_txbytes < 0) {
$net_txbytes = $net->BytesTotalPersec - $net->BytesReceivedPersec;
}
if ($net_rxbytes < 0) {
$net_rxbytes = $net->BytesTotalPersec - $net->BytesSentPersec;
}
return $net_txbytes . "</br>"; //When it RETURNS it only shows the FIRST value... :/ WHAT DO?
}
}
echo win_netinfo();
?>
Output should be like this:
21936313136
12345163517
13647613
87653467
546254
246247
87653642
24583462
(Every other line is Rx or Tx, for each adapter).
Current code that works:
<?php
# Peport All Errors
error_reporting(E_ALL);
# Create Object
$wmi = new COM("Winmgmts://");
# Get net info
$oss = $wmi->execquery("SELECT * FROM Win32_PerfRawData_Tcpip_NetworkInterface");
# Show net info
foreach($oss as $os)
{
echo "BytesReceivedPerSec: " . $os->BytesReceivedPerSec . "<br />";
echo "BytesSentPerSec: " . $os->BytesSentPerSec . "<br />";
echo "BytesTotalPerSec: " . $os->BytesTotalPerSec . "<br />";
echo "Caption: " . $os->Caption . "<br />";
echo "CurrentBandwidth: " . $os->CurrentBandwidth . "<br />";
echo "Description: " . $os->Description . "<br />";
echo "Frequency_Object: " . $os->Frequency_Object . " kb<br />";
echo "Frequency_PerfTime: " . $os->Frequency_PerfTime . "<br />";
echo "Frequency_Sys100NS: " . $os->Frequency_Sys100NS . "<br />";
echo "Name: " . $os->Name . "<br />";
echo "OutputQueueLength: " . $os->OutputQueueLength . "<br />";
echo "PacketsOutboundDiscarded: " . $os->PacketsOutboundDiscarded . "<br />";
echo "PacketsOutboundErrors: " . $os->PacketsOutboundErrors . "<br />";
echo "PacketsReceivedNonUnicastPerSec: " . $os->PacketsReceivedNonUnicastPerSec . "<br />";
echo "PacketsReceivedPerSec: " . $os->PacketsReceivedPerSec . "<br />";
echo "PacketsReceivedUnicastPerSec: " . $os->PacketsReceivedUnicastPerSec . "<br />";
echo "PacketsReceivedUnknown: " . $os->PacketsReceivedUnknown . "<br />";
echo "PacketsSentNonUnicastPerSec: " . $os->PacketsSentNonUnicastPerSec . "<br />";
echo "PacketsSentPerSec: " . $os->PacketsSentPerSec . "<br />";
echo "PacketsSentUnicastPerSec: " . $os->PacketsSentUnicastPerSec . "<br />";
echo "Timestamp_Object: " . $os->Timestamp_Object . "<br />";
echo "Timestamp_PerfTime: " . $os->Timestamp_PerfTime . "<br />";
echo "Timestamp_Sys100NS: " . $os->Timestamp_Sys100NS . "<br />";
echo "<br /><br /><br />";
}
?>
Your returning after the first iteration hence only 1 result, below is how i would do it by creating an array and returning that instead:
<?php
//windows network usage testing
function win_netinfo(){
$wmi = new COM("Winmgmts://");
$nets = $wmi->execquery("SELECT * FROM Win32_PerfRawData_Tcpip_NetworkInterface WHERE BytesSentPersec > 1");
$return=array();
$i=0;
foreach ($nets as $net){
$return[$i]['name']=$net->Name;
if ($net->BytesSentPersec < 0) {
$return[$i]['net_txbytes'] = $net->BytesTotalPersec - $net->BytesReceivedPersec;
}else{
$return[$i]['net_txbytes'] = $net->BytesSentPersec;
}
if ($net->BytesReceivedPersec < 0) {
$return[$i]['net_rxbytes'] = $net->BytesTotalPersec - $net->BytesSentPersec;
}else{
$return[$i]['net_rxbytes'] = $net->BytesReceivedPersec;
}
$i++;
}
return $return;
}
$adapters=win_netinfo();
/*Array
Array
(
[0] => Array
(
[name] => VirtualBox Host-Only Ethernet Adapter
[net_txbytes] => 5095956
[net_rxbytes] => 0
)
[1] => Array
(
[name] => Belkin 54g Wireless USB Network Adapter
[net_txbytes] => 532337967
[net_rxbytes] => 5252455518
)
)
*/
?>
And to output the array, something like this:
<?php
foreach($adapters as $adapter){
echo '<p>'.$adapter['name'].' - Sent: '.$adapter['net_txbytes'].' bytes - Received: '.$adapter['net_rxbytes'].' bytes</p>';
}
?>

Categories