开发者

php problem with function and eval on array

I have function:

开发者_StackOverflow
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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜