【问题标题】:PHP remove a value from arrayPHP从数组中删除一个值
【发布时间】:2017-11-21 13:35:23
【问题描述】:

我正在尝试创建一个字典网站,但遇到了一些问题。我正在将数组的第一个值打印到网站。我正在尝试检查提交到文本框中的输入是否与我网站上显示的单词的翻译相同。如果是,那么我需要从数组中删除该元素,以便现在数组的第一个值将是原始数组中的第二个值,依此类推,直到数组为空。之后,我会有一个数组,其中包含用户不知道如何翻译的单词。

所以我的问题是,如何从数组中删除一个元素,以免索引混乱?或者有没有更好的方法来解决我的问题?

<?php 
$servername = "localhost";
$username = "stud";
$password = "stud";
$dbname = "zodynas-eng";

//Connection
$conn = new mysqli($servername, $username, $password, $dbname);

//Check
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT * FROM politephrases";
$result = $conn->query($sql);

//Create an empty array
$array = array();

if ($result->num_rows > 0) {
// output data of each row
    while($row = $result->fetch_assoc()) {
        $array[] = $row;
    }
}

echo "<br>";

//shuffle($array);

echo "<h2>Word: </h2>";

$i = 0;
echo $array[$i]['word'];
echo '<form name = "tr" method = "post" action = "polite-phrases-eng.php">
        <br>
        <input type = "text" value = "" name = "translation">
        <input type = "submit" name = "submit1" value = "Vykdyti">
    </form>';
if(!empty($_POST)){
    if($array[$i]['transl'] == $_POST) {
        echo "<br> Good job";

        //Remove an element from array
    }
    else {
        //Save the element from input to wrongGuessArray
    }
}
else {
    echo "<br><p>Translation</p>";
}

$conn->close();
?>

【问题讨论】:

标签: php arrays


【解决方案1】:

可以使用 unset 或 array_splice,例如:

$arr = array('a','b','c','d');
unset($arr[1]);

如果您不知道索引或键,您可以使用 array_search 查找数组的索引或键

【讨论】:

  • 这似乎并没有删除它。当我输入正确的值并按提交页面刷新时,显示的值数组 [0] 与以前相同。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-19
  • 2016-05-23
  • 1970-01-01
相关资源
最近更新 更多