php problem with function and eval on array

99封情书 提交于 2019-12-12 04:01:28

问题


I have function:

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

It outputs:

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

It should output:

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

Any ideas ?

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

Thanks.


回答1:


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

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



来源:https://stackoverflow.com/questions/7574437/php-problem-with-function-and-eval-on-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!