Count items separated by semicolons in table field mysql

0

I have a table in the mysql database where tags field values are stored in this format:

+-----------------+
| tags            |
+-----------------+
| B27;C38;H45;B27 |
| C38;H45         |
| B24;C45;L55;K98 |
+-----------------+

I need to count, via mysql or php, the unique items in that column, row by row, so that the result brings me the count of unique items:

B27 -> 2
C38 -> 2
H45 -> 2
B24 -> 1
C45 -> 1
L55 -> 1
K98 -> 1

Thank you in advance.

    
asked by anonymous 22.10.2018 / 19:57

2 answers

1

Use the explode(";", $tags) function to remove ';' to separate the tags, and array_count_values() to count how many equal items it contains in the array:

<?php
$tags = 'B27;C38;H45;B27;C38;H45;B24;C45;L55;K98';
$array = array(explode(";", $tags));
var_dump(array_count_values($array[0]));

foreach (array_count_values($array[0]) as $key => $value) {
    echo $key." => ".$value."\n";
}
    
23.10.2018 / 19:07
1

If I get it right, you'll get the data and put it in an array without repeating the items.

I considered that the data will all be in a variable separated by ; , otherwise it may join them all in one variable and wheels the code below.

Follow the code and php:

//Dados recebidos
$field = "B27;C38;H45;B27;C38;H45;B24;C45;L55;K98";

//Separa os dados em um array
$tags = explode(';', $field);

$countTags = array();

//Percorre o array e junta itens repitidos mostrando sua quantidade
foreach ($tags as $tag) {
    if(array_key_exists($tag, $countTags)){
        $countTags[$tag] += 1;
    }else{
        $countTags[$tag] = 1;
    }
}

//Mostra o array
var_dump($countTags);
    
23.10.2018 / 18:38