使用变量索引定义数组

时间:2014-06-26 21:14:42

标签: php arrays

我的代码:

$rank_content = file('https://www.championsofregnum.com/index.php?l=1&ref=gmg&sec=42&world=2');
    $line_count = 0;
//initializing only the first few keys because of no reason (the latter ones aren't in use yet)
$rankNameArr = array(0=>42,1=>42,2=>42,3=>42,4=>42,5=>42,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72);
$rankRlmpArr = array(0=>42,1=>42,2=>42,3=>42,4=>42,5=>42,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72);
while ($line = array_shift($rank_content)) { // retrieving line after line of the website, does work indeed
    $line_count += 1;
    if(strpos($line, "Warrior #") || strpos($line, "Archer #") || strpos($line, "Mage #"))
    {
        $rankNameArr[$line_count] = $line_count + 1; // HERE nothing happens
        $rankRlmpArr[$line_count] = $line_count + 2; // nothing happens here, too
    }
}

为什么

echo $rankNameArr[2];
echo $rankRlmpArr[2];

给我值42而不是正确值?如果我用实数替换$line_count,则脚本可以正常运行。

我的目的是将值$line_count + 1存储到位置$rankNameArr的{​​{1}}。实际上并不复杂

编辑------------- 请忘掉上面的一切。我最终将脚本缩小到实际问题:

$line_count

这令人遗憾地回应42.我不知道如何 $arr = array(0=>42,1=>42,2=>42,3=>42,4=>42,5=>42,6=>42); $counter=0; for($i=0;$i<7;$i++) { $arr[$counter]=$i; } echo $arr[5]; 存储$arr[$counter]的实际值。

1 个答案:

答案 0 :(得分:1)

  

我不知道如何让$ arr [$ counter]存储$ i的实际值。

$counter设置为0,因此$arr[$counter]$arr[0]相同。如果您回显$arr[0],您会看到 正在被更改,而其余部分保持不变,这意味着您的代码正在运行。

但是,如果您希望$counter也增加,您只需告诉它这样做:

$arr = array(0=>42,1=>42,2=>42,3=>42,4=>42,5=>42,6=>42);
$counter=0;
for($i=0;$i<7;$i++) {
  $counter++;
  $arr[$counter]=$i;
}
echo $arr[5];