0

我正在寻找执行以下操作的最有效方法...

我有一个包含三个字段的表:ideventidmovetype - 我有以下代码来查询数据库中具有匹配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" }

然后我需要检查输出以查看是否满足以下条件:

  1. 数组是否包含Internal 两次
  2. 如果数组只包含一次Internal ,那么数组是否还包含IncomingOutgoing

如果满足任一条件,则应显示一条消息,告诉他们满足哪个条件,否则应显示一条消息,告诉他们条件尚未满足。

我尝试过使用许多 PHP 函数,例如 in_array(),还尝试将数据存储在字符串中并使用 preg_match(),但是这两种方法都没有成功。

4

2 回答 2

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;

    }
}
于 2012-07-11T01:59:44.467 回答
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';
}
于 2012-07-11T02:05:45.117 回答