0

In this example, how to calculate in each row how many NULL values, how many zeros(0) and how many ones(1) and each values store in a variable.

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

I dont know how to do this, but I am trying with the following code

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

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

Please help me to solve this. Thanks

1
  • Consider revising your schema Commented May 6, 2019 at 17:38

1 Answer 1

2

array_walk - Apply a user supplied function to every member of an array

array_count_values - Counts all the values of an array

You can use array_walk,array_count_values function, for example

$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);

output

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

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

    )

)
Sign up to request clarification or add additional context in comments.

3 Comments

Could you please answer me some more specific?
Thanks Rakesh, code works fine. Only a small doubt, if values 0 (zero) is not in DB, it shows an error 'Undefined offset: 0'. The same way is NULL is not there it shows error. How to solve it, sorry for the disturbance Rakesh
@user2594154 the result is displaying based on the array values, if array have 0 you should get the 0 index else not

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.