函数和数组求值的php问题
我有以下职能:函数和数组求值的php问题,php,eval,Php,Eval,我有以下职能: function selects($sql,$tmpl) { preg_match_all('/{[^}]*}/', $tmpl, $m); foreach($m[0] as $key => $val) { $find[] = $val; $replace[] = '$row[\''.str_replace(array('{','}'),"",$val).'\']'; } eval($replace); while($row = mysql_fetch_array(
function selects($sql,$tmpl) {
preg_match_all('/{[^}]*}/', $tmpl, $m);
foreach($m[0] as $key => $val) {
$find[] = $val;
$replace[] = '$row[\''.str_replace(array('{','}'),"",$val).'\']';
}
eval($replace);
while($row = mysql_fetch_array($sql))
{
$selects .= str_replace($find, $replace, $tmpl)."\n";
}
return $selects;
}
echo selects($country_sql,'<option value="{id}">{name}</option>');
函数选择($sql,$tmpl){
preg_match_all('/{[^}]*}/',$tmpl,$m);
foreach($m[0]作为$key=>$val){
$find[]=$val;
$replace[]='$row[\''.str_replace(数组('{','}'),'',$val)。'\'];
}
评价(替换);
while($row=mysql\u fetch\u数组($sql))
{
$selects.=str\u replace($find,$replace,$tmpl)。“\n”;
}
返回$selects;
}
echo选择($country_sql,{name}');
它输出:
<option value="$row['id']">$row['name']</option>
$row['name']
它应该输出:
<option value="1">something</option>
<option value="2">something</option>
...
什么
某物
...
有什么想法吗
我写这个函数是因为我有很多不同的选择,我需要不同的模板
谢谢。考虑到
$country\u sql
是一个sql语句,这对我来说很有用
<?php
function selects($sql,$template) {
preg_match_all('/{([^}]*)}/', $template, $matches);
$result = mysql_query($sql); //were missing this?
$select = '';
while($row = mysql_fetch_assoc($result)){
$aux = $template;
for($i = 0; $i < count($matches[0]); $i++){
$aux = str_replace($matches[0][$i], $row[$matches[1][$i]],$aux);
}
$select .= $aux."\n";
}
return $select;
}
echo "<select>";
echo selects($country_sql,'<option value="{id}">{name}</option>');
echo "</select>";
?>
为什么要使用eval
?你需要考虑你想要完成什么<这里不需要code>eval
而不是用PHP代码替换模板,为什么不直接用值替换呢,即,str\u replace($find,$row[$replace],$tmpl)
并用字段名而不是PHP代码填充$replace。如果$country\u sql
是sql语句,那么您就缺少了$res=mysql\u查询($country\u sql)
可以,谢谢,函数中不需要mysql\u查询,因为我已经在$sql变量中向函数发送了mysql数组。