在sql中用逗号分隔的字符串计算相同的项目

时间:2017-09-15 10:58:17

标签: php mysql sql codeigniter

嗨我在数据库中有逗号分隔的id。 我想单独计算/百分比(GROUP BY)并想制作饼图。怎么做?

喜欢,附上示例数据库图片。

Id         COUNT
1-----------6 OR some%
15----------3 OR some%
17----------2 OR some%
2-----------2 OR some%
6-----------2 OR some%
12----------1 OR some%

Database records (Example)

3 个答案:

答案 0 :(得分:0)

试试这个

假设您在$result中获得了数据  然后

$result['count']=count(explode(",",$result['column_name']));

答案 1 :(得分:0)

除了您的数据库结构完全混乱之外,您还可以尝试以下操作:

$arrData = [
    "1","15,17","1","1","15,17","1","1","1,2","6,7,12,16","9,10","2,4,6,7","14,15,16"
];

$arrCounts = [];

array_walk($arrData, function($item, $key) use (&$arrCounts)    {
    foreach(explode(",",$item) AS $val)
    {
        if (!isset($arrCounts[$val]))   $arrCounts[$val] = 0;
        $arrCounts[$val]++;
    }
});
ksort($arrCounts);
print_r($arrCounts);

答案 2 :(得分:-1)

将包含逗号分隔的数字的变量转换为具有explode()的数组,并计算数组的项目。

$string = '1,2,3,4';
$array = explode(',',$string);
echo "String contains ".count($array)." items";