使用 foreach 从数据库中输出数据

我有一个非常简单的数据库,一个包含 8 种语言的列表,它们可以具有的值为 Y 或 N。我需要为每种语言输出一个复选框,如果值为 Y,则必须选中该复选框,否则它必须是空的。这是我用于每种语言的代码,但我想知道是否有更好的方法来获得相同的结果。


if ($language=='N'){

echo "<input type='checkbox' name='" . $rowlang["english"] . "' value='" . $rowlang["english"] . "'> English<br>";

} else {

echo "<input type='checkbox' name='" . $rowlang["english"] . "' value='" . $rowlang["english"] . " checked'> English<br>";}


//What I've tried to do is to build an array of the languages and use a foreach

$languages = array($rowlang["czech"],$rowlang["english"],$rowlang["german"],$rowlang["slovak"],$rowlang["russian"],$rowlang["french"],$rowlang["spanish"],$rowlang["italian"]);


foreach($languages as $language)

if ($language=='N'){

echo "<input type='checkbox' name='" . $language . "' value='" . $language . "'> " . $rowlang . "<br>";

}else{

echo "<input type='checkbox' name='" . $language . "' value='" . $language . "' checked> " . $rowlang . "<br>";

}

这几乎可以正常工作,问题是我无法回显单一语言,因为使用此代码我得到了“数组”。


牧羊人nacy
浏览 236回答 3
3回答

白衣染霜花

首先创建一个关联数组并将语言及其值存储在其中:$languages = array('czech' => 'N','english' => 'Y','german' => 'N','slovak' => 'N','russian' => 'N','french' => 'N','spanish' => 'Y','italian' => 'N' );然后:foreach($languages as $key => $value) {&nbsp; &nbsp; if ($value=='N'){echo "<input type='checkbox' name='" . $key . "' value='" . $value . "'> " . $key . "<br>";&nbsp; &nbsp; }&nbsp; &nbsp; else{&nbsp;echo "<input type='checkbox' name='" . $key . "' value='" . $value . "' checked> " . $key . "<br>";&nbsp; &nbsp; }&nbsp;}结果将是:

料青山看我应如是

问题在于,尝试将其用作数组的$rowlang一部分echo是一个问题,因为它是一个数组。相反,您可以创建一个您想要输出的语言数组,这也给出了要显示为值的名称。所以foreach()在这个数组上使用 a并检查$rowlang数组以查看它是否已设置。而不是重复整个 HTML,这只是设置checked属性。// Need to expand this array for all the countries you need$languages = array("german" => "Germany","english" => "English");foreach($languages as $language => $label)&nbsp; &nbsp;{&nbsp; &nbsp; if ($rowlang[$language]=='N'){&nbsp; &nbsp; &nbsp; &nbsp; $checked = '';&nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; $checked = ' checked';&nbsp; &nbsp; }&nbsp; &nbsp; echo "<input type='checkbox' name='" . $language . "' value='" . $language . "'$checked>" . $label . "<br>";}这将输出类似<input type='checkbox' name='german' value='german'>Germany<br><input type='checkbox' name='english' value='english' checked>English<br>

梦里花落0921

如果是数组,则应使用$language->language_name或$langage['language_name']作为数组类型
打开App,查看更多内容
随时随地看视频慕课网APP