我有一个这样的MySQL表;
╔════╦═══════════════════════╗
║ id ║ comma_separated_stuff ║
╠════╬═══════════════════════╣
║ 1 ║ 1, 2, 3, 4, 5 ║
║ 2 ║ 1, 2, 5 ║
║ 3 ║ 3, 7 ║
║ 4 ║ 4, 8 ║
╚════╩═══════════════════════╝
我设法将每一行放入数组中,如array[0], array[1], array[2]和array[3]。问题是如何计算"有多少逗号分隔的数组包含——例如——‘5’?"
<?php
//how many of the comma-separated-arrays include for example '5'
$array = array(
'1, 2, 3, 4, 5',
'1, 2, 5',
'3, 7',
'4, 8',
);
$n = 5;
$sum = 0;
//Split the strings to arrays of numbers
foreach($array as $value)
{
$data = explode(', ', $value);
if (in_array($n, $data))
{
++$sum;
}
}
//prints 2
print $sum;
如果您想通过以下两个示例来计算数组本身中有多少个键:
<?php
$a[0] = '1, 2, 3, 4, 5';
$a[1] = '1, 2, 5';
$a[2] = '3, 7 ';
$a[3] = '4, 8';
$resulta = count($a);
print $resulta;// Output 4
?>
另一个:
<?php
$b = array ('1, 2, 3, 4, 5','1, 2, 5' ,'3, 7','4, 8');
$resultb = count($b);
print $resultb;// Output 4
?>
如果您想从字符串中计算逗号的个数,请使用下面的一个:
$text = 'This , is, , a , test a,a,';
echo substr_count($text, ','); // Output 6 , will give the number of comma in each one