每个循环的PHP?一定有更好的方法

时间:2012-07-02 00:32:31

标签: php for-loop foreach

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



?>

上面的示例应该在运行时可以使用此播放器查看输出 - .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])

-

然后我试图将每个$ data []索引分解成3个部分,就像我上面的方式一样,但是我希望能够为每个循环执行一些事情来遍历每个$ data []索引并使用explode(“,”,$ data [0])分解每个;爆炸(“,”,$ data [1]);爆炸(“,”,$ data [2]);但每次都会有索引增量。我最终需要的是每个值都可以在我可以使用的变量中。例如:

$apple = number_format($stats0[0]);
echo $apple;

这是我尝试过的东西:

$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++;
}

1 个答案:

答案 0 :(得分:0)

而不是一次又一次地重复自己,创建一个像这样的函数:

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

并在循环中调用它。