我有一个像这样的 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'?”
最佳答案
<?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 - 如何计算从数据库表中检索到的包含 PHP 中特定值的逗号分隔数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32206292/