php返回数组

时间:2011-10-30 14:20:02

标签: php sql codeigniter foreach

使用codeigniters mvc,我为我的搜索查询创建了一个模型,我希望将其作为数组返回。

我有点迷失,我创建了一个foreach语句,以便我可以对每个字符串执行一个函数。 (不确定它是否是正确的方法,现在想将它作为数组传递给我的$ data变量。

有人能指出我正确的方向,并强调我做错了什么:

<?php

class Search_model extends CI_Model {

            function search($searchquery)
    {

                function supertruncate($text, $searchquery, $characters_before, $characters_after){
                  $pos = strpos($text, $searchquery);
    $start = $characters_before < $pos ? $pos - $characters_before : 0;
    $len = $pos + strlen($word) + $characters_after - $start;
                   $text =  substr($text, $start, $len);
                   $last = strrpos($text, ' ');

                  return  str_ireplace($word, '<span class="highlight" style="background: #E6E6E6;">' . $word . '</span>', $text);
}

     $this->db->from('content');
$this->db->like('title', $data);
$this->db->or_like('content', $data);
$query = $this->db->get();

$characters_before="120";
 $characters_after="120";

foreach ($query ->result() as $row)
{
    $title =  strip_tags($row->title);
   $text = supertruncate(strip_tags($row->content), $searchquery, $characters_before, $characters_after);

}

    return $data;

    }

}

1 个答案:

答案 0 :(得分:0)

模型:

...
$results = Array();
foreach ($query->result() as $row)
{
    $results[] = Array(
        'title' => strip_tags($row->title),
        'text' => upertruncate(strip_tags($row->content), $searchquery, $characters_before, $characters_after)
    );
}
return $results;
...

控制器:

$this->load->model('Search');
$data['search_results'] = $this->Search->Search('Invest');
$this->load->view('template', $data);

视图:

<div id="search_results">
    <?php foreach($search_results as $result): ?>
    <h1><?php echo $result['title']; ?></h1>
    <div><?php echo $result['text']; ?></div>
    <?php endforeach; ?>
</div>