传递单个或多个URI段以实现功能(代码点火器)

时间:2012-01-17 13:06:41

标签: php codeigniter uri

目前我有这个网址来查看db(codeigniter)domain.com/view/id

中的图像

我希望能够接受多个ID逗号分隔domain.com/view/id,id,id

知道如何去做吗?感谢


查看控制器部分:

function view() {
    $id = alphaID($this->uri->segment(1) ,true);

    $this->load->model('Site_model');
    if($query = $this->Site_model->get_images($id)) {
        $data['records'] = $query;
    }   
    $this->load->view('view', $data);


}

<?php if(isset($records)) : foreach($records as $row) : ?>
    <?php if($row->alpha_id == $this->uri->segment(1)): ?>
        <h1><?php echo $row->alpha_id.$row->file_ext; ?></h1>
    <?php endif; ?>
    <?php endforeach; ?>
<?php endif; ?>

3 个答案:

答案 0 :(得分:3)

在控制器中使用此功能

function view() {
    $id = $this->uri->segment(1);
    $id_array = explode(",", $id);
    $this->load->model('Site_model');
    foreach ($id_array as $key => $id) {
    // use alphaID function
    $id = alphaID($id ,true);
    if($query = $this->Site_model->get_images($id)) {
        $data['records_array'][$key] = $query;
    // added second array for comparison in view
        $data['id_array'][$key] = $id;
    } 
    }  
    $this->load->view('view', $data);
}

供您查看:

<?php 
foreach ($records_array as $key => $records) {
if(isset($records)) : foreach($records as $row) : ?>
    // removed uri and added array
    <?php if($row->alpha_id == $id_array[$key]):    ?>
        <h1><?php echo $row->alpha_id.$row->file_ext; ?></h1>
    <?php endif; ?>
    <?php endforeach; ?>
<?php endif; 
}
?>

答案 1 :(得分:1)

因为逗号不是有效的路径元素,所以如果没有右侧的分隔数据,您将无法使其工作?字符。你需要提出另一个方案或者使用@jprofitt的评论。

答案 2 :(得分:1)

你是对的,你可以在$config['permitted_uri_chars']中添加一个逗号,但除非你挂钩到系统核心,否则你每次需要时都必须操纵该段。

尚未测试此代码,但您会明白:

<?php

$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-,'; // Note a comma...

// Controller
class Blog extends CI_Controller
{

    public function posts($ids = NULL)
    {
        // Check if $ids is passed and contains a comma in the string
        if ($ids !== NULL AND strpos($ids, ',') !== FALSE)
        {
            $ids = explode(',', $ids);
        }

        // Convert $ids to array if it has no multiple ids
        is_array($ids) OR $ids = array($ids);

        // $ids is an array now...

    }

    public function new_posts()
    {
        // Check if $ids is passed and contains a comma in the string
        $ids = $this->uri->segment(1);
        if (!empty($ids) AND strpos($ids, ',') !== FALSE)
        {
            $ids = explode(',', $ids);
        }

        // Convert $ids to array if it has no multiple ids
        is_array($ids) OR $ids = array($ids);

        // $ids is an array now...

    }

}

?>

example.com/index.php/blog/posts/2,4,6,8

请再次注意,代码可能不准确,因为我没有对其进行测试,但认为它会对您有所帮助。