2016-07-15 77 views
0

型號製作自定義網址笨

function get_footer_pages(){ 
    $query=$this->db->where('section','footer'); 
    $query=$this->db->get('pages'); 
    if($query->num_rows()>0){ 
     $result=$query->result_array(); 
     return $result; 
    }else{ 
     return false; 
    } 
} 
function get_url($row){ 
    $title=$row['title']; 
    $not_allowed=array('/','?','\"','&','"',':','%','\'',','); 
    $title=str_replace($not_allowed,'',$title); 
    $title=str_replace(' ','-',$title); 
    $title=$title."_".$row['id']; 
    return $title; 
} 

控制器:

$data['footer_pages']=$this->Home_model->get_footer_pages(); 

查看:

<?php foreach($footer_pages as $f_pages){ ?> 
     <li><a href="<?php echo $f_pages['url'] ?>"><?php echo $f_pages['name'] ?></a></li> 
<?php } ?> 

我想創建一個正如我在功能get_url()執行組合和id

現在的問題:

是我怎麼能叫這個get_url()get_footer_pages()做出的get_footer_pages()所有結果的URL和href使用的網址,我VIEW

回答

0

如果你要使用在所有的你的意見這一功能,倒不如將它放在助手(並確保你自動加載該助手)。然後,在你看來,你將有:

<?php foreach($footer_pages as $f_pages){ ?> 
    <li><a href="<?php echo get_url($f_pages) ?>"><?php echo $f_pages['name'] ?></a></li> 
<?php } ?> 

這將動態生成的URL - 通過他們再次每當你需要顯示它,而不是產生在一次所有的URL,然後迭代,以顯示他們在視圖中。

現在你已經在頁腳您的網址,您需要妥善處理。首先,你需要創建你的路由文件的路徑,將捕獲想要的網址,並將其傳遞給的應該處理的動作控制器。您尚未指定該部分,因此以下是一個基於您可以創建自己的路線的示例。

$route['product/:num'] = 'catalog/product_lookup/$1'; 

這樣做什麼是,當應用程序接收到像example.com/product/1的請求時,它實際上調用catalog控制器的product_lookup函數並傳遞1作爲函數參數。

+0

你的手段我必須在助手文件夾中創建一個文件任何名稱,然後'get_url()'保存在幫助文件中。並在我看來調用該函數? –

+0

是的。你需要在你的'application/config/autoload.php'文件中將這個幫助文件添加到helpers autoload數組中。 – trajchevska

+0

如果我在我的視圖中執行get_url()的所有功能,那麼? –

0

使用助手:

創建一個文件,把下面的代碼到它。

<?php if (! defined('BASEPATH')) exit('No direct script access allowed'); 

    if (! function_exists('getPages')) 
    { 
    function getPages() 
    { 
     $ci = & get_instance(); 
     $ci->load->model('yourModelname'); 
     return $ci->yourModelname->get_footer_pages(); 
    } 
    } 

將其保存到應用程序/幫助程序/。我們將其稱爲 「my_helper.php」

使用助手

$this->load->helper('my_helper'); 

// You can also use this; 

    $autoload['helper'] = array('new_helper'); 

模型方法:

function get_footer_pages() 
{ 
    $data = array(); 
    $this->db->where('section','footer'); 
    $query = $this->db->get('pages'); 
    if ($query->num_rows() > 0){ 
     foreach ($query->result_array() as $row) { 
      $title = $row['title']; 
      $not_allowed = array('/','?','\"','&','"',':','%','\'',','); 
      $title = str_replace($not_allowed,'',$title); 
      $title = str_replace(' ','-',$title); 
      $title = $title."_".$row['id']; 
      $data['urls'] = $title; 
     } 
    } 
    return $data; 
    } 

在教職員:

<?php 
    $footer_pages = getPages(); 
    foreach($footer_pages['urls'] as $f_pages){ ?> 
    <li><a href="<?php echo $f_pages['url'] ?>"><?php echo $f_pages['name'] ?></a></li> 
<?php } ?>