How can I dynamically increase a number in PHP
I want to add number dynamically and aiming the outputs as follows.
<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>
I tried this, but it does not work.
Views:
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";
}
}
If there are two images, it repeats twice, if there are three, it repeats three times and so on.
I have the following controller and model.
Controller:
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);
}
Model:
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;
}
if I get the question right you just want to increase the number. best thing is to keep it one loop like this:
$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++;
}
Since it looks like you don't care about the array key, you can just use that:
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";
}
精彩评论