PHP用列值计算每一行并存储在变量中

时间:2019-05-06 17:24:05

标签: php mysql

在此示例中,如何计算每行中有多少NULL值,多少个零(0)以及多少个零(1)以及每个值存储在一个变量中。

+-------+--------+--------+--------+--------+--------+--------+--------+--------+--------+
| 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 |
+-------+--------+--------+--------+--------+--------+--------+--------+--------+--------+

O / p

**StdID = 3**
$null = 2;
$zeros = 2;
$ones = 5;

**StdID = 4**
$null = 1;
$zeros = 3;
$ones = 5;

我不知道该怎么做,但是我正在尝试以下代码

$check = isset($day1['day1S1'])  ? "1" : "0"; doesnt work

$values = $day1['day1S1']+$day1['day1S2']+$day1['day1S3'] etc

请帮助我解决此问题。谢谢

1 个答案:

答案 0 :(得分:2)

  

array_walk-将用户提供的函数应用于数组的每个成员

     

array_count_values-计算数组的所有值

例如,您可以使用array_walkarray_count_values函数

$arr = [
  'StdID' => [
    '3' => ['NULL',1,0,1,1,0,'NULL',1,1],
    '4' => [1,1,0,1,0,0,'NULL',1,1]
  ]
];
$res=[];
array_walk($arr['StdID'], function($v, $k) use (&$res){
   $res['StdID'][$k] = array_count_values($v);
});
echo '<pre>';
print_r($res);

输出

Array
(
  [StdID] => Array
    (
        [3] => Array
            (
                [NULL] => 2
                [1] => 5
                [0] => 2
            )

        [4] => Array
            (
                [1] => 5
                [0] => 3
                [NULL] => 1
            )

    )

)