我有一个像这样的MySQL表;
╔════╦═══════════════════════╗
║ id ║ comma_separated_stuff ║
╠════╬═══════════════════════╣
║ 1 ║ 1, 2, 3, 4, 5 ║
║ 2 ║ 1, 2, 5 ║
║ 3 ║ 3, 7 ║
║ 4 ║ 4, 8 ║
╚════╩═══════════════════════╝
我设法将每一行作为数组[0],数组[1],数组[2]和数组[3]进入数组。问题是如何计算“有多少逗号分隔数组包含 - 例如 - '5'?”
答案 0 :(得分:1)
<?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;
答案 1 :(得分:0)
以下两个示例,如果您想通过以下方式计算数组本身中的键数:
<?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