我的目的是在我的fancybox中添加一个动态值,我必须生成一个从数据库中提取的JSON。
以下是我在Code Igniter中的模型中的当前代码:
function get_gallery_list($album) {
$query = $this->db->query('SELECT id, img_name, caption FROM tb_gallery WHERE album = "'.$album.'"');
$tags = array('img_name', 'caption');
$replacementTags = array('html', 'title');
$json = str_replace($tags, $replacementTags, json_encode($query->result()));
$search_array = array_fill(0, sizeof($replacements), $search_pattern);
$result = preg_replace($search_array, $replacements, $subject, 1);
return $json;
}
//img_name is replace with html, caption = title.
/* returns: [{"id":"1","html":"roadshow2012_1.jpg","title":"WOW"},{"id":"2","html":"roadshow2012_1.jpg","title":"Wew"}] */
示例:
感谢那些愿意回答的人!:D
答案 0 :(得分:0)
当你可以这样做时,你不会这样做。它的工作量较少,其他人也不容易遵循
$sql='SELECT id,
CONCAT("directlink-to-localhost/images/gallery/",img_name) AS html,
caption AS title
FROM tb_gallery
WHERE album = "'.$album.'"';
$query = $this->db->query($sql);
return json_encode($query->result());
...
我不应该按照你提出的方式发布如何做到这一点,因为它有点疯狂,但如果你必须...
当str_replace更快时,你没有充分的理由使用preg_replace。
$query = $this->db->query('SELECT id, img_name, caption FROM tb_gallery WHERE album = "'.$album.'"');
$find = array('"img_name":"', '"caption"');
$replace = array('"html":"directlink-to-localhost/images/gallery/', '"title"');
$result=str_replace($find, $replace, json_encode($query->result());
return $json;
我无法看到db类,因此假设query-> result()符合您的预期。