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

<?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.

Related

Illegal String Offset in Multidimensional Array

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];
}
?>

PHP Read Text File With Column Separated

I have a text file generated from our banking software which looks like this:
This is my code to print the text file contents line by line:
<?php
$myFile = "20151231.txt";
$lines = file($myFile);
foreach ($lines as $line_num) {
echo htmlspecialchars($line_num)."<br>";
}
It prints like this:
I just want each line that starts with:
====>
I want everything else deleted.
I tried a lot but failed to print lines with the columns separated as it looks in the text file image.
This is how I want each line to print:
====>0518 Intt on Consumer Loan 401010707 108,149.00
Your assistance regarding this will be highly appreciated.
You can print it as a table:
<?php
$myFile = "20151231.txt";
$lines = file($myFile);
echo '<table>';
foreach ($lines as $line_num) {
if (strpos($line_num, '====>') !== false) {
$str = trim(htmlspecialchars($line_num));
echo '<tr>';
echo '<td>' . getColumnText("/====>\d+/", $str) .'</td>';
echo '<td>' . getColumnText("/\s([a-zA-Z\s]+)/", $str) .'</td>';
$secondCol = getColumnText("/\s([0-9]+)/", $str);
echo '<td>' . $secondCol .'</td>';
$thirdCol = end(explode(" ", $str));
if (trim($secondCol) === $thirdCol) {
echo '<td style="text-align:right">' . str_repeat(" ", 10) .'</td>';
} else {
echo '<td style="text-align:right">' . str_repeat(" ", 10) . $thirdCol .'</td>';
}
echo '</tr>';
}
}
echo '</table>';
function getColumnText($pattern, $str) {
preg_match($pattern, $str, $matches);
return trim(current($matches));
}
yes you can do that with strpos or regularexpression and i am just writing code using strpos
<?php $myFile = "text.txt";
$lines = file($myFile);
echo '<table cellspacing="20">';
$linenum = 1;
foreach ($lines as $line_num) {
echo '<tr>';
// check whether line conatain ====>, if you want to check starting of line then just put 0 instead of false in following condition
if(strpos($line_num,'====>')!==false)
{
$texts= substr($line_num, strpos($line_num,'====>')+5);
$textarr = explode(" ", $texts);
echo '<td>'.$linenum.'</td>';
foreach($textarr as $arr)
{
echo '<td>'.$arr.'</td>';
}
$linenum++;
//print_r($textarr);
//echo htmlspecialchars($line_num)."<br>";
}
}
echo '<table>';

How to store each word in a string into specific variables?

Please help me to put these words of string into some specific variables.
$remove4 = "First 1st, Second 2nd, Third 3rd, Fourth 4th";
i'm using this code, but i can get it right. can somebody tell me what is the problem in my code?
$str = (explode(",",$remove4));
$check = array();
for($i=0;$i<=$count;$i++){
$check[] = $str[$i];
}
foreach($check as $value){
echo $value . "<br>";
$var=(explode(" ", $value));
echo $var[0];
echo $var[1];
}
Goal:
Process1 = 'First';
Process2 = 'Second';
Process3 = 'Third';
Process4 = 'Fourth';
Temp1 = '1st';
Temp2 = '2nd';
Temp3 = '3rd';
Temp4 = '4th';
$remove4 = "First 1st, Second 2nd, Third 3rd, Fourth 4th";
$str = (explode(",",$remove4));
$check = array();
$i=0; foreach ($str as $value) { $i++;
$explode = (array_values(array_filter(explode(" ",$value))));
${'Process'.($i)} = $explode[0];
${'Temp'.($i)} = $explode[1];
}
echo $Process1 . "<br /> ";
echo $Process2 . "<br /> ";
echo $Process3 . "<br /> ";
echo $Process4 . "<br /> ";
echo $Temp1 . "<br /> ";
echo $Temp2 . "<br /> ";
echo $Temp3 . "<br /> ";
echo $Temp4 . "<br /> ";
Output :
First
Second
Third
Fourth
1st
2nd
3rd
4th
you can try this
foreach($check as $key => $value){
//echo $value . "<br>";
$var=(explode(" ", $value));
${'Process'.($key+1)} = $var[0];
${'Temp'.($key+1)} = $var[1];
}
echo $Process1;
echo $Temp3;

Echo all values in php array as a sentence

Is it possible to display an array as a sentence? So between each of the values there would be ", " except before the last value there would be " and ".
I have taken this little piece of code to use within an example:
<?php
$cars=array("Volvo","BMW","Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
This works great for three values but I need it to work for between 1 and 15 values.
Thanks
$carsCount = count($cars);
if ($carsCount == 1) {
$sentence = $cars[0] . '.';
} else {
$partial = array_slice($cars, 0, $carsCount-1);
$sentence = implode(', ', $partial) . ' and ' . $cars[$carsCount-1];
}
echo $sentence;
$array = array("Volvo", "BMW", "Toyota");
$sentence = '';
foreach($array as $k => $v) {
if (count($array) == 1) {
$sentence = $v;
break;
}
else if ($k == count($array)-1) {
$sentence .= 'and ' . $v;
}
else {
$sentence .= $v . ', ';
}
}
echo $sentence;
Above returns the following: Volvo, BMW, and Toyota
There is another way [shorter], [faster].
$cars = array("Volvo", "BMW", "Toyota", "Fiat");
if (count($cars) > 1) {
$lastVal = array_pop($cars);
echo implode(",", $cars)." and ".$lastVal;
} else {
echo $cars[0];
}

PHP - remove comma from the last loop

I have a PHP while LOOP, and I want to remove last comma , from echo '],'; if it is last loop
while($ltr = mysql_fetch_array($lt)){
echo '[';
echo $ltr['days']. ' ,'. $ltr['name'];
echo '],';
}
Create an array with the elements as you go along so that they look like array = ([ELEMENT INFO], [ELEMENT INFO], [ELEMENT INFO]) and then implode the array with a comma.
$str = '';
while($ltr = mysql_fetch_array($lt)){
$str .= '[';
$str .= $ltr['days']. ' ,'. $ltr['name'];
$str .= '],';
}
echo rtrim($str, ",");
this will remove the last , from string
I think the systemic solution is following:
$separator = '';
while($ltr = mysql_fetch_array($lt)){
echo $separator;
echo '[';
echo $ltr['days']. ' ,'. $ltr['name'];
echo ']';
if (!$separator) $separator = ', ';
}
No call for count(), no additional iteration of implode(), no additional string operations, ready for any (unpredictable) number of results.
$result = mysql_fetch_array($lt);
for ($i=0;$i<=(count($result)-1);$i++) {
$ltr = $result[$i];
echo '[';
echo $ltr['days']. ' ,'. $ltr['name'];
echo ']';
if(!count($result)-1 == $i){
echo ',';
}
}
Check how many entries you have, make a "Counter" and a condition to only put the comma when its not the last loop.
$arr = array();
while($ltr = mysql_fetch_array($lt)){
$arr[] = '[' . $ltr['days'] . ' ,' . $ltr['name'] . ']';
}
echo implode(',', $arr);
$res_array = array();
while($ltr = mysql_fetch_array($lt)){
$res_array[] = '['.$ltr['days']. ' ,'. $ltr['name'].']';
}
$str = implode(",",$res_array);
echo $str;
Save the response as a var instead of echoing it and then remove the final character at the end using substr.
$response = "";
while($ltr = mysql_fetch_array($lt)){
$response .= '[';
$response .= $ltr['days']. ' ,'. $ltr['name'];
$response .= '],';
}
echo substr($response, 0, -1);
//this one works
$result = mysql_fetch_array($lt);
for ($i=0;$i<=(count($result)-1);$i++) {
$ltr = $result[$i];
echo '[';
echo $ltr['days']. ' ,'. $ltr['name'];
echo ']';
if(count($result)-1 != $i){
echo ',';
}
}

Categories