将单个或多个URI段传递给函数(代码点火器)


Pass single OR multiple URI segments to function (code igniter)

目前我有这个url来查看来自db(代码点火器)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; ?>

在控制器中使用此功能

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; 
}
?>

因为逗号不是有效的路径元素,如果没有在?性格你需要想出另一个方案,或者接受@jprofitt的评论。

您是对的,您可以在$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

请再次注意,代码可能不准确,因为我还没有测试过它,但认为它会帮助你。