我正在寻找最有效的方法来执行以下操作...
我有一个包含三个字段的表: id , eventid 和 movetype - 我有以下代码来查询所有数据库匹配 eventid 的条目:
$get_results = mysql_query("SELECT * FROM table WHERE eventid='$eventid'");
while($row = mysql_fetch_array($get_results)){
// store results in array
$move_type_array = explode(" ", $row['movetype']);
}
请注意: movetype 只能是三个值:Internal,Outgoing,Incoming
使用一组虚拟数据, var_dump($ move_type_array)可以输出:
array(1) { [0]=> string(8) "Internal" } array(1) { [0]=> string(8) "Internal" }
输出的另一个例子是:
array(1) { [0]=> string(8) "Internal" } array(1) { [0]=> string(8) "Incoming" } array(1) { [0]=> string(8) "Outgoing" }
然后我需要检查输出以查看是否满足以下条件:
如果满足其中任何一个条件,则应显示一条消息,告诉他们已满足哪个条件,否则消息应告诉他们条件未满足。
我尝试过使用许多PHP函数,比如in_array(),并尝试将数据存储在字符串中并使用preg_match()但是我在这两种方法中都没有成功。
答案 0 :(得分:0)
// 1. Don't use '*' - fetch only required fields!
// 2. Don't use mysql_* functions - they are obsolete! Use PDO or MySQLi instead.
$get_results = mysql_query("SELECT `movetype` FROM table WHERE eventid='$eventid'");
while($row = mysql_fetch_array($get_results)){
// Count the values
$arr = array_count_values(explode(" ", $row['movetype']));
// Check them here
if(isset($arr['Internal'])) {
if($arr['Internal'] === 2)
echo ' Internal: 2'.PHP_EOL;
else if($arr['Internal'] === 1
&& isset($arr['Incoming'])
&& isset($arr['Outgoing']))
echo ' Internal: 1, Incoming and Outgoing'.PHP_EOL;
}
}
答案 1 :(得分:0)
试试这个:
$result = mysql_query("
SELECT SUM(IF(movetype = 'Internal', 1, 0)) AS internal,
SUM(IF(movetype = 'Outgoing', 1, 0)) AS outgoing,
SUM(IF(movetype = 'Incoming', 1, 0)) AS incoming
FROM table
WHERE eventid = $eventid
GROUP BY eventid
");
$count = mysql_fetch_array($result);
if ($count['internal'] >= 2 || ($count['internal'] == 1
&& $count['outgoing'] >= 1
&& $count['incoming'] >= 1)) {
echo 'Yes';
} else {
echo 'No';
}