无法正确设置 php 键值对

cant set php key-value pair set properly

我在 class 中使用了一个键值对,但它没有按照我想要的方式返回数据。我想让GB&Lv中的值在键区,值在值区。但是,我的调试输出似乎表明我当前将值放在键值对的键部分?

class Player{
    var $PlayerName ;
    var $TotalContributedPoints;
    function GetTotalContributedPoints()
    {
            $mysqli = new mysqli("localhost", "user", "password", "foe_gb_contribs_test");
        if ($mysqli->connect_errno) {
           echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
        }

        $debug = true;

        if ($debug == true) {echo $this->PlayerName.'<br>';}
        $QuerySQL = "SELECT * FROM `GB_Contribs` WHERE Player_Nick = '".$this->PlayerName."' order by DATE ASC";
        if ($debug == true) {echo 'Query is '.$QuerySQL.'<br>';}
        $ContribArray = array("Key" => "Value");
        $result = $mysqli->query($QuerySQL);
        if ($result->num_rows > 0) {
            while($row=$result->fetch_assoc()) {
                $ContribArray[$row['GB&Lv']] = $row['Value'];
            }
            foreach($ContribArray as $key => $value) {
                echo "Player_nick: ". $this->PlayerName ."<br>";
                echo "Great Building Level: ".$ContribArray[$key]."<br>";
                echo "Contribution Points".$ContribArray[$value]."<br>";
            }
            return $ContribArray;

        }  else {
            if ($debug == true) {echo "0 results";}
            return;
        }


    }

}// END of Player Class

当您使用 foreach 迭代数组时,您已经有了键和值。您不需要再次引用该数组。

foreach($ContribArray as $key => $value) {
    echo "Player_nick: ". $this->PlayerName ."<br>";
    echo "Great Building Level: ".$key."<br>";         // not $ContribArray[$key]
    echo "Contribution Points".$value."<br>";          // not $ContribArray[$value]
}

实际上,$ContribArray[$key] 为您提供了价值,我认为 $ContribArray[$value] 不会为您提供任何东西。事实上,它似乎可能会导致未定义的索引通知。