我想通过数组将$view['time']
值替换为%time%
来显示数据库值。
例
如果$view['time']='8;00 pm';
我写%time%
这里显示晚上8点。
它适用于单个原始,但是当我尝试通过循环显示值时,这里只显示第一个值是我的代码,请面颊并帮助我。
<?php
$msg='
<div class="pad9">
<img src="http://trickround.xtgem.com/files/licon.gif"/>
<a href="%post-id%"> %post-title% </a>
<br/>
<div class="lined"> </div>
<font color="fuchsia"> </font>
<font color="red">%time%</font>
</div>
<div class="lines"></div>';
$post1 = $conn->prepare('SELECT * FROM post WHERE id_user = :id order by id DESC LIMIT 10');
$post1->execute(array(':id' => '4'));
while ($view = $post1->fetch(PDO::FETCH_ASSOC)) {
$bbcode = array(
'%post-title%' => htmlentities($view['title'], ENT_QUOTES, 'UTF-8'),
'%post-messge%' => $view['message'],
'%time%' => $view['time'],
'%post-id%' => ''.$view['id'].'.html',
'%post-url%' => ''.$view['url'].'.html'
);
$msg = str_replace(array_keys($bbcode), array_values($bbcode), $msg);
echo $msg;
}
请给出解决方案我如何获得所有获取值。
你在每次迭代时都会覆盖原始字符串$msg
。在第一次迭代之后,字符串$msg
将包含第一次迭代的数据,其中所有占位符都已被替换。
而不是将结果存储在$msg
中,只需直接在循环中回显结果。
更改:
$msg = str_replace(array_keys($bbcode), array_values($bbcode), $msg);
echo $msg;
只是:
echo str_replace(array_keys($bbcode), $bbcode, $msg);
正如@mickmackusa指出的那样,没有必要使用array_values()
作为第二个参数,因为str_replace()
只使用数组值。