首页 > 解决方案 > php if elseif 循环不能正常工作

问题描述

我有以下 php 代码。它不工作。要么它只是检查 if 条件。如果在 If 中没有找到,则直接跳转到 else 部分并打印 Neutral。

在我下面的代码中。我声明了三个数组。一个带有否定词的数组,第二个带有建议词的数组,第三个带有否定词的数组。然后我拿一个字符串并一一检查该字符串/文本是否有否定词。如果是则打印否定,否则检查建议字数组。如果在文本中找到任何建议词,则打印建议。如果没有找到建议词,则转到正数组并在其中搜索,依此类推...

在我下面的代码中,它应该打印“positve”,但它打印的是“neutral”

<?php

$neg_words= array('not good',
'poor',
'late',
'wrong');


$sug_words=array('would',
'should',
'suggestion',
'want');

$pos_words=array('Great',
'great',
'good',
'smile',
'pleasant',
'interesting',
'pleasing',
'nice',
'happy',
'love',
'like',
'loving',
'liking',
'amazing');

$string = 'I like the way';

$tmp =explode(' ', $string);

$strings=end($tmp);




if (in_array($strings,$neg_words)):
echo "Negative"; 
elseif (in_array($strings,$sug_words)):
 echo "Suggestion"; 
elseif (in_array($strings,$pos_words)):
echo "positive";
else:
 echo "Neutral"; 

endif;



?>

标签: phparraysif-statement

解决方案


上面代码中的问题,不需要end()。

<?php

$neg_words= array('not good',
'poor',
'late',
'wrong');

$sug_words=array('would',
'should',
'suggestion',
'want');

$pos_words=array('Great',
'great',
'good',
'smile',
'pleasant',
'interesting',
'pleasing',
'nice',
'happy',
'love',
'like',
'loving',
'liking',
'amazing');

$string = 'I like the way';

$strings =explode(' ', $string);





if (array_intersect($strings,$neg_words))
echo "Negative"; 
elseif (array_intersect($strings,$sug_words))
 echo "Suggestion"; 
elseif (array_intersect($strings,$pos_words))
echo "positive";
else
 echo "Neutral"; 




?>

推荐阅读