-1

In a table unit, I have 18 columns which can contain one of three different values in each of the columns. The possible values are 'N', 'I' or 'ETP'.

Three of those columns are:

|------------|-------------|------------|
|gcc_1_1     |gcc_1_2      |gcc_1_3     |
|------------|-------------|------------|

I want to return counts of each of those three values for each column to put into their own variables, e.g. the following variables would be for the first column and the three possible values.

$gcc_1_1_n
$gcc_1_1_i
$gcc_1_1_etp

What would be the simplest way of achieving this in PHP using one MySQL query?

  $query = "SELECT * FROM unit";
    $result = $connection->query( $query );
    while ($row = mysqli_fetch_array($result)) {
       ...
    }

   
2
  • The best method in terms of performance and ease would be to do it directly in PHP. Commented Nov 3, 2021 at 7:30
  • stackoverflow.com/questions/15815011/… Commented Nov 3, 2021 at 7:34

1 Answer 1

1

you could do something like this

<?php
$data = [...]; //array of data in the form of [['gcc_1_1' => 'n',... ], ...]
 
$groupedData = array_reduce(
   $data,
   function(array $res, array $row){
      foreach($row as $column => $value) {
        $key = $column.'_'.$value;
        $existing = $res[$key] || 0;
        $res[$key] = $existing + 1;
       }
      return $res;
    }, 
  []
);


Now in your $groupedData you have an array with keys that matches your request. You can use extract() to create n variables but I think you shouldn't do it because it's harder to handle and debug for future issues

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

Comments

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.