我想动态添加数字并按如下方式瞄准输出。
<li data-id="id-1".. > ...</li>
<li data-id="id-2".. > ...</li>
<li data-id="id-3".. > ...</li>
<li data-id="id-4".. > ...</li>
<li data-id="id-5".. > ...</li>
<li data-id="id-6".. > ...</li>
我试过这个,但它不起作用。
查看:
for($i=1; $i<=$image_num; $i++){
foreach($images as $image){
echo "<li data-id=\"id-".$i."\" data-type=\"".$image['class']."\">\n<img src=\"".base_url().$image['thumbnail']."\" width=\"128\" height=\"128\" />\n<strong>".$image['name']."</strong>\n<span data-type=\"size\">".$image['shortdesc']."</span></li>\n";
}
}
如果有两个图像,则重复两次,如果有三个,则重复三次,依此类推。
我有以下控制器和模型。
控制器:
function quicksand(){
$data['header']='Quicksand';
$group = 'quicksand';
$data['image_num']= $this->MQuicksand->getNumRowsByGroup($group);
$data['images']= $this->MQuicksand->getProductsByGroup($group);
$data['module'] = 'welcome';
$this->load->view('general/quicksand_temp',$data);
// $this->load->view('welcome/public/quicksand_view',$data);
}
型号:
function getProductsByGroup($group){
$data = array();
$this->db->where('grouping', $group);
$this->db->where('status', 'active');
// $this->db->orderby('name','asc');
$Q = $this->db->get('omc_product');
if ($Q->num_rows() > 0){
$num_rows = $Q->num_rows();
foreach ($Q->result_array() as $row){
$data[] = $row;
}
}
$Q->free_result();
return $data;
return $num_rows;
}
function getNumRowsByGroup($group){
$data = array();
$this->db->where('grouping', $group);
$this->db->where('status', 'active');
// $this->db->orderby('name','asc');
$Q = $this->db->get('omc_product');
if ($Q->num_rows() > 0){
$num_rows = $Q->num_rows();
}
$Q->free_result();
return $num_rows;
}
答案 0 :(得分:4)
如果我的问题正确,你只想增加数字。最好的办法就是保持这样一个循环:
$count = 1;
foreach($images as $image){
echo "<li data-id=\"id-".$count."\" data-type=\"".$image['class']."\">\n<img src=\"".base_url().$image['thumbnail']."\" width=\"128\" height=\"128\" />\n<strong>".$image['name']."</strong>\n<span data-type=\"size\">".$image['shortdesc']."</span></li>\n";
$count++;
}
答案 1 :(得分:1)
因为看起来你不关心数组键,所以你可以使用它:
foreach($images as $elem => $image){
echo "<li data-id=\"id-".($elem + 1)."\" data-type=\"".$image['class']."\">\n<img src=\"".base_url().$image['thumbnail']."\" width=\"128\" height=\"128\" />\n<strong>".$image['name']."</strong>\n<span data-type=\"size\">".$image['shortdesc']."</span></li>\n";
}