php - 检查数组中的值

标签 php mysql arrays if-statement

希望有人能帮忙!

我在周末成功完成了我的测验,该测验是一个 10 个问题/多项选择/多项答案类型的场景 - 但今天早上简介发生了变化 -

事实证明,例如问题1:

Q How do you make tea
A) Water
B) Teabag
C) Cup
D) Fish Tank

客户希望 A B C 是正确答案,但还有其他正确答案,例如:-

A - Is correct + 1 to score
B - Is correct + 1 to score
C - Is Correct + 1 to score
A & B - Is correct  + 1 to score
A & C - Is correct + 1 to score
B & A - Is correct + 1 to score
B & C - Is correct + 1 to score
A & B & C - Is the Jackpot! + 1 to score

在此“修正”之前,我已将结果存储到问题数据库中作为 A、B、C - 所以一切正常 - 所以我相信我必须“分解”原始数组,以便它们是单独的数组元素(我假设这样做会更容易) - 所以我的数组现在看起来像这样:

    Array ( [0] => A [1] => B [2] => C ) 

我尝试执行 if 嵌套 if 语句:

    if($vex['0'] == 'A')
    {
    echo "Yup, it equals A";
    if($vex['1'] == 'B')
    {
    echo "Yup, it equals B";
    } 

但我意识到数组可能并不总是以 [0] => A 等开头

可以帮助我并为我指明正确的方向吗?

将复选框存储为单个值而不是数组并仅进行检查会更简单吗?

最佳答案

使用数组和intersect他们得分如下:

$user_choices = array('A', 'C');
$valid_choices = array('A', 'B', 'C');

$common = array_intersect($user_choices, $valid_choices); // A,C
$score = count($common); // 2

同样:

choices A     -> common = A     -> score = 1
choices D     -> common =       -> score = 0
choices A,B,C -> common = A,B,C -> score = 3

关于php - 检查数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14567124/

相关文章:

php - Laravel Eloquent 非常规专栏不起作用

mysql - 如何对另一列的 DISTINCT 值和 GROUP BY 日期求和?

javascript - 在对象数组上使用 forEach() 后样式化 div

C# 字符串拆分和合并

javascript - 将多维数组组合成基于键的字典对象

php - 仅打印一次数组中的值

重写动态url后的Javascript文件路径

php - Knockout JS 和 Chosen 多选不工作

mysql - 如何显示 SQL 中字段中输入的数据总数

mysql - 仅当列不存在时才使用 SQL 将列添加到 MySQL(不是 MariaDB)表