问题描述
我需要检查从数据库接收到的词与用户输入的词,如果匹配,则从数据库中输出其值,如果不匹配,则输出用户输入的内容。
如果匹配,下面的代码可以正常工作。
function d_typeplace_morf($d_typeplace)
{
global $wpdb;
$typeplace_results = $wpdb->get_results('SELECT vozmozhnyi_variant_mesta,ego_slovoforma_v_predlozhnom_padezhe FROM dEzpra_jet_cct_tip_mest_obrabotki');
if ($typeplace_results) {
foreach ($typeplace_results as $typeplace_result) {
$d_typeplace_raw = mb_strtolower($typeplace_result->vozmozhnyi_variant_mesta);
$d_typeplace_morf = mb_strtolower($typeplace_result->ego_slovoforma_v_predlozhnom_padezhe);
$d_typeplace = mb_strtolower($d_typeplace);
if (stripos($d_typeplace,$d_typeplace_raw) !== false) {
echo $d_typeplace_morf;
}
}
}
}
我是 PHP 的业余爱好者,只是在学习。如果找不到匹配项,我不知道如何输出 $d_typeplace
。
我尝试添加
else {
echo $d_typeplace;
}
,但我从输入的用户那里得到了一组单词。
我将不胜感激任何帮助。还有关于改进此代码的任何建议。
---添加---
我为我的英语道歉。这是俄语的问题,我需要考虑形态。为此,数据库有一个单词及其类似物的列表,例如 X = Y
。我得到这些词并比较用户输入的内容。如果他输入X
,那么我们输出Y
。如果他带领Z
,它不在数据库中,那么我们输出Z
。
因此,我们用$d_typeplace
检查$d_typeplace_raw
,如果匹配,我们输出$d_typeplace_morf
,它等于$d_typeplace_raw
。如果不是,则 $d_typeplace
(它包含用户输入的值)。
哦,对不起,我明白自己在解释很愚蠢)
解决方法
我猜你是想像这样添加 else 吗?
function d_typeplace_morf($d_typeplace)
{
global $wpdb;
$typeplace_results = $wpdb->get_results('SELECT vozmozhnyi_variant_mesta,ego_slovoforma_v_predlozhnom_padezhe FROM dEzpra_jet_cct_tip_mest_obrabotki');
if ($typeplace_results) {
foreach ($typeplace_results as $typeplace_result) {
$d_typeplace_raw = mb_strtolower($typeplace_result->vozmozhnyi_variant_mesta);
$d_typeplace_morf = mb_strtolower($typeplace_result->ego_slovoforma_v_predlozhnom_padezhe);
$d_typeplace = mb_strtolower($d_typeplace);
if (stripos($d_typeplace,$d_typeplace_raw) !== false) {
echo $d_typeplace_morf;
} else {
echo $d_typeplace;
}
}
}
}
输出数组是因为 for 循环仍在继续,如果您像这样添加中断...
echo $d_typeplace;
break;
它应该停止输出数组。但是,根据您的用例,您可以使用 LIKE ...
直接在 sql 查询中执行类似的功能function d_typeplace_morf($d_typeplace)
{
global $wpdb;
$typeplace_results = $wpdb->get_results('
SELECT ego_slovoforma_v_predlozhnom_padezhe
FROM dEzpra_jet_cct_tip_mest_obrabotki
WHERE vozmozhnyi_variant_mesta LIKE %' . $d_typeplace . '%');
if ($typeplace_results) {
//Echo result
} else {
echo $d_typeplace;
}
}
,
我不太明白你在问什么:你需要输出用户输入的字符串,但你只能打印一个数组?
如果是这种情况,我认为您之前解析了字符串,因此您需要再次连接数组中包含的值。
尝试:
else {
echo implode(" ",$d_typeplace);
}
--- 编辑---
尝试:
function d_typeplace_morf($d_typeplace)
{
global $wpdb;
$typeplace_results = $wpdb->get_results('SELECT vozmozhnyi_variant_mesta,ego_slovoforma_v_predlozhnom_padezhe FROM dEzpra_jet_cct_tip_mest_obrabotki');
if ($typeplace_results) {
$found = false;
foreach ($typeplace_results as $typeplace_result) {
$d_typeplace_raw = mb_strtolower($typeplace_result->vozmozhnyi_variant_mesta);
$d_typeplace_morf = mb_strtolower($typeplace_result->ego_slovoforma_v_predlozhnom_padezhe);
$d_typeplace = mb_strtolower($d_typeplace);
if (stripos($d_typeplace,$d_typeplace_raw) !== false) {
echo $d_typeplace_morf;
$found = true;
break;
}
}
if (!$found) {
echo $d_typeplace;
}
}
}
但我认为如果你实现@Luke.T 编写的第二个代码片段会更有效率