用特定变量替换 php echo 输出

Replace php echo output with certain variable

我有一个 mysql 数据 table 和 "itemLevels"(数字)。因此,如果我回显项目级别,我希望它们被替换为特定文本。

itemLevels 1 => Text1; itemLevels 2 => 文本 2; itemLevels => Text3

目前我有以下代码:

<?php
$con = mysqli_connect("localhost","XXXXXX","XXXXX","XXXXX");


// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }



/* change character set to utf8 */
if (!mysqli_set_charset($con, "utf8")) {
    printf("Error loading character set utf8: %s\n", mysqli_error($con));
    exit();
} else {

}

$sql = "SELECT * FROM TEST WHERE name=test";

$result = mysqli_query($con,$sql)or die(mysqli_error());

echo "<table>";


while($row = mysqli_fetch_array($result)) {
    $name= $row['name'];
    $itemLevel= $row['itemLevel'];


    echo
"<tr><td class='name'>".$name."</td></tr>
<tr><td class='name'>Gegenstandsstufe ".$itemLevel."</td></tr> 
</tr>";
}

echo "</table>";
mysqli_close($con);
?>

我读过 "php str_replace" 但我不确定它是否正确以及如何在我的代码中使用它。

你可以只使用数组

$itemLevelNames = [
    0 => 'Text0',
    1 => 'Text1',
    2 => 'Text2',
    42 => 'Text42',
    // and so on
];

然后通过

输出文本
echo $itemLevelNames[$itemLevel];