Foreach循环不能在codeigniter模型和控制器中工作

时间:2013-08-15 21:51:44

标签: codeigniter

我简单的foreach循环工作该死的很奇怪,请帮我解决这个问题

这是我的控制器代码

public function index()
{
    $this->load->model('file_list');
    $query = 'SELECT * FROM `files_data` WHERE file_extension = "jpg" and size > 0 LIMIT 0,10';
    foreach($this->db->query($query)->result() as $file){
        $data['check'] = $this->file_list->preview_maker($file->file_id, $file->file_full_path, $file->file_extension);
    }

    //$this->load->view('viewtest', $data);


    //$this->home_footer();

}

这里是模特

public function preview_maker($file_id, $file_full_path, $extension){
    if(file_exists('preview/'.$file_id.'.jpg')){
        $preview = 'preview/'.$file_id.'.jpg';
    } else {
        if($extension == 'jpg' || $extension == 'gif' || $extension == 'png'){
            $config = array(
            'source_image' => 'stuff'.$file_full_path, //get original image
            'new_image' => 'preview/'.$file_id.'.jpg', //save as new image //need to create thumbs first
            'maintain_ratio' => true,
            'width' => 80,
            'height' => 80
                    );

            $this->load->library('image_lib', $config); //load library
            $this->image_lib->resize(); //do whatever specified in config
            $preview = '/preview/'.$file_id.'.jpg';
        } elseif ($extension == 'mp3'){
            $preview = '/preview/music.jpg';
        } elseif ($extension == 'apk'){
            $preview = '/preview/android.jpg';
        } elseif ($extension == 'jar'){
            $preview = '/preview/java.png';
        } elseif ($extension == 'zip'){
            $preview = '/preview/zip.jpg';
        } elseif ($extension == '3gp' || $extension == 'mp4' || $extension == 'avi'){
            $preview = '/preview/movie.png';
        }
    }
    return $preview;
}

问题是,foreach循环不能连续工作,它只为每次刷新工作1条记录,然后下次记录下次刷新

2 个答案:

答案 0 :(得分:1)

正如@prix试图告诉你的那样,

foreach($this->db->query($query)->result() as $file){
    $data['check'] = $this->file_list->preview_maker($file->file_id, $file->file_full_path, $file->file_extension);
}

应该阅读

foreach($this->db->query($query)->result() as $file){
    $data['check'][] = $this->file_list->preview_maker($file->file_id, $file->file_full_path, $file->file_extension);
}

否则你只是继续写下你的价值。

另请阅读http://php.net/manual/en/control-structures.switch.php

答案 1 :(得分:0)

实际上这件事对我有用...... 我有关于生成拇指的问题

$config = array(
            'source_image' => 'stuff'.$file_full_path, //get original image
            'new_image' => 'preview/'.$file_id.'.jpg', //save as new image //need to create thumbs first
            'maintain_ratio' => true,
            'width' => 80,
            'height' => 80
                    );

            $this->image_lib->initialize($config);
            $resize = $this->image_lib->resize();
            $this->image_lib->clear(); //do whatever specified in config
            $preview = '/preview/'.$file_id.'.jpg';

我没有使用

$this->image_lib->clear(); 

上次