php函数和数组上的评估问题 [英] php problem with function and eval on array

查看:55
本文介绍了php函数和数组上的评估问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有功能:

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>');

它输出:

<option value="$row['id']">$row['name']</option>

它应该输出:

<option value="1">something</option>
<option value="2">something</option>
...

有什么想法吗?

我之所以编写此函数,是因为我有许多不同的选择,并且需要不同的模板.

I wrote this function because I have many different selects and I need different templates for them.

谢谢.

推荐答案

考虑到$country_sql是一个sql语句,这对我有用

This works for me considering $country_sql is a sql statement

<?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>";
?>

您可以将<select>部分添加到函数中,但这取决于您.

You could add the <select> part to the function but that's up to you.

这篇关于php函数和数组上的评估问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆