PHP:用自然语言翻译每周日历可用性?

时间:2015-03-07 22:38:37

标签: javascript php algorithm nlp

我的数据库用户的每周可用性存储如

Monday Morning - yes
Monday Afternoon - yes
Monday Night - NO
Tuesday Morning - yes
Tuesday Afternoon - yes
Tuesday Night - NO
Wednesday Morning - yes
Wednesday Afternoon - yes
Wednesday Night - NO
etc.

基本上是一个矩阵7x3,我正试图找到一种用

这样的语言来表达它的方法

Mike可用"MON-WED, Morning thru afternoon"

或类似的......

我的大脑正在爆炸,以了解解决这个问题的最佳方法。

我正在使用PHP,但可以是JS或其他......

2 个答案:

答案 0 :(得分:1)

7种可能的组合(从最具体到最少):

Morning, Afternoon, Night
Morning, Afternoon
Morning, Night
Afternoon, Night
Morning
Afternoon
Night

您可以识别与识别unix权限的方式类似的组合:

$111 = "Morning - Night";
$110 = "Morning - Afternoon";
$101 = "Morning - Night";
$011 = "Afternoon - Night";
$100 = "Morning";
$010 = "Afternoon";
$001 = "Night";

下一步是将天数与数组中各自的值匹配, 考虑一周中的几天为0-6(星期一)的整数。周日的可用性为ex。应该是索引0,星期一,1等等。

设置执行以下操作的循环。对于每一天,从一个空字符串开始。如果给定时间可用,请附加" 1"到字符串。如果没有,请追加" 0"。

这就是你的数组应该如何看待循环

$day[0] = "110";
$day[1] = "110";
$day[2] = "110";
$day[3] = "011";
$day[4] = "011";
$day[5] = "100";
$day[6] = "110";

现在只需将具有相同值的$day元素组织成组即可。首先显示最大的组。一种方法是使用这样的数组:

$array = []
$array["110"] = "012", "6"
$array["011"] = "34"
$array["100"] = "5"

请注意,6并不是在2之后,所以它作为另一个元素插入到数组[" 110"]中,而不是附加到" 012"。

接下来,按长度订购组:

012 => 110
34 => 011
5 => 100
6 => 110

现在转换为英语:

Su - Tu: Morning - Night
W - Th: Morning - Night
F: Morning - Night
Sa: Morning - Night

答案 1 :(得分:0)

由于它是一个矩阵,因此最好将其显示为矩阵,否则文本组合太多而且对于应用程序的用户来说很难理解。

$s = 'Monday Morning - yes
Monday Afternoon - yes
Monday Night - NO
Tuesday Morning - yes
Tuesday Afternoon - yes
Tuesday Night - NO
Wednesday Morning - yes
Wednesday Afternoon - NO
Wednesday Night - yes';

$a = array();

foreach(explode("\n", $s) as $line) {
    $p = explode(' ', trim($line));
    if(!isset($a[$p[0]])) {
        $a[$p[0]] = array();
    }
    $a[$p[0]][$p[1]] = $p[count($p) - 1] == 'yes' ? true : false;
}

// the availability matrix
echo '<pre>';print_r($a);echo '</pre>';

/* this would print:
Array
(
    [Monday] => Array
        (
            [Morning] => 1
            [Afternoon] => 1
            [Night] => 
        )
    [Tuesday] => Array
        (
            [Morning] => 1
            [Afternoon] => 1
            [Night] => 
        )
    ...
)
 */

// this matrix can be displayed in a friendly way like this
$rows = array('Morning', 'Afternoon', 'Night');
$cols = array('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday');
echo '<table>';
echo '<tr>';
echo '<td>&nbsp;</td>';
foreach($cols as $col) {
    echo '<td>'.substr($col, 0, 3).'</td>';
}
echo '</tr>';
foreach($rows as $row) {
    echo '<tr>';
    echo '<td>'.$row.'</td>';
    foreach($cols as $col) {
        echo '<td style="background-color:'.(isset($a[$col][$row]) && $a[$col][$row] ? 'green' : 'red').';">&nbsp;&nbsp;&nbsp;</td>';
    }
    echo '</tr>';
}
echo '</table>';

// a nice table with green and red cells will be displayed