循环数组并添加,在所有行和列中查找相同的ID

时间:2019-05-07 11:53:00

标签: php mysql arrays

循环数组并添加,在所有行和列中查找相同的ID。

我的桌子

+-------+--------+--------+--------+--------+--------+--------+--------+--------+--------+
| StdID | day1S1 | day1S2 | day1S3 | day2S1 | day2S2 | day2S3 | day3S1 | day3S2 | day3S3 |
+-------+--------+--------+--------+--------+--------+--------+--------+--------+--------+
|     3 | NULL   |      1 |      0 |      1 |      1 |      0 | NULL   |      1 |      1 |
|     4 | 1      |      1 |      0 |      1 |      0 |      0 | NULL   |      1 |      1 |
|     3 | 1      |      0 |      0 |      1 |      1 |      0 | 1      |      1 |      1 |
|     3 | NULL   |      1 |      0 |      1 |      1 |      0 | NULL   |      0 |      0 |
|     4 | 0      |      1 |      1 |      1 |      1 |      0 | NULL   |      0 |      0 |
+-------+--------+--------+--------+--------+--------+--------+--------+--------+--------+

我正在使用以下代码

$stu_leave          = "SELECT * FROM tblname WHERE StdID = '3' ";
$stu_leave_result   = $conn->query($stu_leave);

while($stu_leave_result_fetch   = $stu_leave_result->fetch_assoc()) 
{
    $array = array("$day1S1","$day1S2","$day1S3","$day2S1","$day2S2","$day2S3","$day3S1","$day3S2","$day3S3");

    $counts = array_count_values($array);
    echo $counts['1']."<br>";
    echo $counts['0'];
}

这是我的输出

5 6 3 
2 3 4

我希望得到的结果为

14 (add all 5 + 6 + 3).
9

请帮助我。

3 个答案:

答案 0 :(得分:2)

只需使用array_sum()对值求和。

while ($stu_leave_result_fetch = $stu_leave_result->fetch_assoc()) {
    $counts = array_count_values($array);
    $sum = array_sum($counts);
    echo $sum."<br />\n";
}

答案 1 :(得分:2)

您可以使用array_walk,array_count_values和array_sum满足您的要求

$result = [];
array_walk($a, function ($item) use (&$result) {
    $item = array_filter($item, function ($var) {
        // removing null values
        return ($var !== null);
    });
    $result[] = array_count_values($item);
});

echo array_sum(array_column($result, 1))."<br/>";
echo array_sum(array_column($result, 0));

array_sum —计算数组中的值之和
array_walk —将用户提供的函数应用于数组的每个成员
array_column —从输入数组的单个列中返回值
array_filter —使用回调函数过滤数组的元素

输出

14
9

工作demo

编辑

映射到您的代码,

$result = [];
while($stu_leave_result_fetch   = $stu_leave_result->fetch_assoc()) 
{
    $array = array("$day1S1","$day1S2","$day1S3","$day2S1","$day2S2","$day2S3","$day3S1","$day3S2","$day3S3");
    $array = array_filter($array, function ($var) {
        // fetching null values
        return ($var !== null);
    });
    $result[] = array_count_values($array);
});
echo array_sum(array_column($result, 1))."<br/>";
echo array_sum(array_column($result, 0));

答案 2 :(得分:1)

首先,如果仅查询您实际感兴趣的列,则提取的数组将仅包含要求和的数据。

然后,您可以对返回的行执行简单的array_sum(),使代码更简单易读。

$sql    = "SELECT day1S1, day1S2, day1S3, day2S1, 
                  day2S2, day2S3, day3S1, day3S2, day3S3 
            FROM tblname 
            WHERE StdID = '3'";
$result = $conn->query($sql);

while($row = $result->fetch_assoc()) 
{

    echo array_sum($row) . '<br>';
}