how to display two results per loop in php foreach - arrays

I have a portfolio table where there are number of rows, at the front end side of my website, I have li in which there are div, now i want to display two div in per li like in first li there are portfolio item 1 and portfolio item 2 and next li there are portfolio item 3 and portfolio item 4
following is my code
<ul class="slides">
<?php for($i = 1; $i <= round(count($projlists)/2); $i++) { ?>
<li>
<?php foreach($projlists as $projlist) { ?>
<div class="span3"> <a class="thumbnail" href="#"> <img alt="260x180" data-src="holder.js/260x180" style="width: 260px; height: 180px;" src="<?=base_url()?>uploads/portfolio/full/<?=$projlist->portfolio_image?>"> </a> </div>
<?php } ?>
</li>
<?php } ?>
</ul>
following is my model
function projectlist()
{
$query = $this->db->query("SELECT * FROM portfolio WHERE status = 1");
if($query->num_rows() > 0)
{
foreach($query->result() as $row)
{
$data[] = $row;
}
return $data;
}
}
Note: i am using codeigniter

To show two divs in one li within loop you can do so,define a flag variable and increment it for each iteration of loop and check if the modulus of flag with 2 is zero i.e $index % 2 == 0 then close li and open li
<ul class="slides">
<li>
<?php
$index = 0;
foreach ($projlists as $projlist) {
?>
<div class="span3">
<a class="thumbnail" href="#">
<img alt="260x180" data-src="holder.js/260x180" style="width: 260px; height: 180px;"
src="<?= base_url() ?>uploads/portfolio/full/<?= $projlist->portfolio_image ?>">
</a></div>
<?php $index++;
if ($index % 2 == 0 && $index !=count($projlists)) {
echo '</li><li>';
}
} ?>
</li>
</ul>

Related

How to add div after 3 rows in Joomla intro_items

I'm working on adding this to the com_content blog.php override.
Where we have the intro_items I need to have it count through 3 articles and then add a div where I can drop an ad script and than have it carry on and load the remaining 7 articles.
This is the intro_items loop. In parameters I have it set to 10 articles
<?php
$introcount = count($this->intro_items);
$counter = 0;
?>
<?php if (!empty($this->intro_items)) : ?>
<?php foreach ($this->intro_items as $key => &$item) : ?>
<?php $rowcount = ((int) $key % (int) $this->columns) + 1; ?>
<?php if ($rowcount === 1) : ?>
<?php $row = $counter / $this->columns; ?>
<div class="items-row cols-<?php echo (int) $this->columns; ?> <?php echo 'row-' . $row; ?> row-fluid clearfix">
<?php endif; ?>
<div class="span<?php echo round(12 / $this->columns); ?>">
<div class="item column-<?php echo $rowcount; ?><?php echo $item->state == 0 ? ' system-unpublished' : null; ?>"
itemprop="blogPost" itemscope itemtype="https://schema.org/BlogPosting">
<?php
$this->item = &$item;
echo $this->loadTemplate('item');
?>
</div>
<!-- end item -->
<?php $counter++; ?>
</div><!-- end span -->
<?php if (($rowcount == $this->columns) or ($counter == $introcount)) : ?>
</div><!-- end row -->
<?php endif; ?>
<?php endforeach; ?>
<?php endif; ?>
I came up with the following, which works, but would like an opinion if there is a better way to do this.
<?php
$introcount = count($this->intro_items);
$counter = 0;
?>
<?php if (!empty($this->intro_items)) : ?>
<?php foreach ($this->intro_items as $key => &$item) : ?>
<?php $rowcount = ((int) $key % (int) $this->columns) + 1; ?>
<?php if ($rowcount === 1) : ?>
<?php $row = $counter / $this->columns; ?>
<div class="items-row cols-<?php echo (int) $this->columns; ?> <?php echo 'row-' . $row; ?> row-fluid clearfix">
<?php endif; ?>
<?php if ($row != 2) : ?>
<div class="span<?php echo round(12 / $this->columns); ?>">
<div class="item column-<?php echo $rowcount; ?><?php echo $item->state == 0 ? ' system-unpublished' : null; ?>"
itemprop="blogPost" itemscope itemtype="https://schema.org/BlogPosting">
<?php
$this->item = &$item;
echo $this->loadTemplate('item');
?>
</div>
<?php endif; ?>
<?php if ($row === 2) : ?>
<div class="span<?php echo round(12 / $this->columns); ?>">
<div class="item column-<?php echo $rowcount; ?><?php echo $item->state == 0 ? ' system-unpublished' : null; ?>"
itemprop="blogPost" itemscope itemtype="https://schema.org/BlogPosting">
<?php
$this->item = &$item;
echo $this->loadTemplate('item');
?>
<!-- mobile ad banner zone -->
<div class="cat-banner bannerzonepadding visible-phone">
<script type="text/javascript" language="javascript" src="http://myadsrc.demo"></script>
</div>
</div>
<?php endif; ?>
<!-- end item -->
<?php $counter++; ?>
</div><!-- end span -->
<?php if (($rowcount == $this->columns) or ($counter == $introcount)) : ?>
</div><!-- end row -->
<?php endif; ?>
<?php endforeach; ?>
<?php endif; ?>
Would this approach work?
you add an ID to a wrapper around your list of intro_items
use jQuery and CSS nth-child selector to target the third child in the intro_items list
then use jQuery .after() function to insert the HTML for your ad
Pseudo code
$("#intro_items_wrapper .items-row:nth-child(3)").after('<!-- mobile ad code here -->');
Actual code
$("#intro_items_wrapper .items-row:nth-child(3)").after('<!-- mobile ad banner zone -->
<div class="cat-banner bannerzonepadding visible-phone">
<script type="text/javascript" language="javascript" src="http://myadsrc.demo"></script>
</div>');
Here's a working demo:
https://codepen.io/panchroma/pen/EEwaQX
Good luck!

CakePHP table sorting with bootstrap icons

I want to sort a table by id when clicking on it. It is working but the main thing is that the bootstrap arrow up and down icons should also be attached to the id label.
When the data is displayed in descending order, then the bootstrap arrow-bottom icon should be shown, and when the data is displayed in ascending order, then the arrow-up icon should be shown.
UsersController.php
public $paginate = array('limit'=>4);
public function index() {
$this->User->recursive = 0;
$this->set('users', $this->paginate());
}
index.ctp
<div class="users index">
<h2><?php echo __('Users'); ?></h2>
<table class="zebra-striped table-bordered " cellpadding="0" cellspacing="0">
<tr>
<th>
<a href='' >
<?php echo $this->Paginator->sort('id'); ?>
<i class='icon-arrow-up'></i>
</a>
</th>
<th><a href='' >First Name <i class='icon-arrow-down'></i>
</a> </th>
<th>Last Name <i class='icon-resize-full'></i></a></th>
</tr>
<?php foreach ($users as $user): ?>
<tr>
<td><?php echo h($user['User']['id']); ?> </td>
<td><?php echo h($user['User']['first_name']); ?> </td>
<td><?php echo h($user['User']['last_name']); ?> </td>
</tr>
<?php endforeach; ?>
</table>
<p>
<?php
echo $this->Paginator->counter(array(
'format' => __('Page {:page} of {:pages}, showing {:current} records out of {:count} total, starting on record {:start}, ending on {:end}')
));
?> </p>
<div>
<div class="pagination">
<ul>
<?php
echo $this->Paginator->prev(__('prev'), array('tag' => 'li'),
null, array('tag' => 'li','class' => 'disabled','disabledTag' => 'a'));
echo $this->Paginator->numbers(array('separator' => '','currentTag'
=> 'a', 'currentClass' => 'active','tag' => 'li','first' => 1));
echo $this->Paginator->next(__('next'), array('tag' => 'li','currentClass' => 'disabled'), null, array('tag' => 'li','class' => 'disabled','disabledTag' => 'a'));
?>
</ul>
</div>
A Simple Solution using Jquery, just add the below 3 lines in your default application.js or in layout/default.ctp
$('th a').append(' <i class="icon-sort"></i>');
$('th a.asc i').attr('class', 'icon-sort-down');
$('th a.desc i').attr('class', 'icon-sort-up');
Another Simple CSS Based Solution, Include Font Awesome's necessary files.
th > a:after {
content: " \f0dc";
font-family: FontAwesome;
}
th > a.asc:after {
content: " \f0dd";
font-family: FontAwesome;
}
th > a.desc:after {
content: " \f0de";
font-family: FontAwesome;
}
Use PaginatorHelper::sortDir() to check the current sort direction and build the class name based on that value:
<i class='icon-arrow-<?php echo $this->Paginator->sortDir() === 'asc' ? 'up' : 'down'; ?>'></i>
To embed this into a sort link, pass the HTML as the second parameter to PaginatorHelper::sort(), and set the escape option to false:
$type = $this->Paginator->sortDir() === 'asc' ? 'up' : 'down';
$icon = "<i class='icon-arrow-" . $type . "'></i>";
echo $this->Paginator->sort('id', $icon, array('escape' => false));
That should result in a link like:
<i class='icon-arrow-up'></i>
You need also check a key, so it would be
<?php echo $this->Paginator->sort('title', 'My great title'); ?>
<?php if ($this->Paginator->sortKey() == 'title'): ?>
<i class='fa fa-sort-<?php echo $this->Paginator->sortDir() === 'asc' ? 'up' : 'down'; ?>'></i>
<?php else: ?>
<i class='fa fa-sort'></i>
<?php endif; ?>

CodeIgniter Pagination create_links() | Results not taking into account 'where' clauses

I have been working on an app in codeigniter which takes a series of optional fields and does a query on the database to return results based on the fields selected. These results are then paginated using the codeigniter pagination library.
The pagination work fine and the results are paginated, the problem is when i for instance get gender to 'male' so that only male results are returned, even though the first page works perfectly, the create_links() function renders pages for every result in the table, and when i change the page all 'where' parameters for the db->get() function are ignored. Any advice with this would be much appreciated.
Code:
Controller:
public function searchcharacter() {
$data = $this->input->post();
$gender = $data['gender'];
$age = $data['approx_age'];
$hairColour = $data['hair_colour'];
$hairLength = $data['hair_length'];
$eyeColour = $data['eye_colour'];
$earType = $data['ear_type'];
$weapons = $data['weapons'];
$this->load->library('pagination');
$config['base_url'] = 'http://localhost/ci-animedb/site/searchcharacter';
$config['total_rows'] = $this->db->get('characters')->num_rows();
$config['per_page'] = 10;
$config['uri_segment'] = 3;
$config['num_links'] = 20;
$this->pagination->initialize($config);
$this->load->model('get_db');
$results['characters'] = $this->get_db->getCharacterList($gender, $age, $hairColour, $hairLength, $eyeColour, $earType, $weapons, $config['per_page']);
$this->load->view('header');
$this->load->view('characterlist', $results, FALSE);
$this->load->view('footer');
}
Model:
function getCharacterList($gender, $age, $hairColour, $hairLength, $eyeColour, $earType, $weapons, $limit) {
if ($gender != "None" && !empty($gender))
{
$this->db->where('gender', $gender);
}
if ($age != "None" && !empty($age))
{
$this->db->where('approx_age', $age);
}
if ($hairColour != "None" && !empty($hairColour))
{
$this->db->where('hair_colour', $hairColour);
}
if ($hairLength != "None" && !empty($hairLength))
{
$this->db->where('hair_length', $hairLength);
}
if ($eyeColour != "None" && !empty($eyeColour))
{
$this->db->where('eye_colour', $eyeColour);
}
if ($earType != "None" && !empty($earType))
{
$this->db->where('ear_type', $earType);
}
if ($weapons != "None" && !empty($weapons))
{
$this->db->where('weapons', $weapons);
}
$query = $this->db->get('characters', $limit, $this->uri->segment(3));
return $query->result();
}
View:
<div class="container">
<div class="row">
<div class="span12">
<img src="<?php echo base_url(); ?>img/banner1.png" alt="AnimeDB.me" />
</div>
</div>
<div class="row">
<div class="span12" style="height:1px; background-color: #cccccc; margin-top: 20px; margin-bottom: 15px;"></div>
</div>
<div class="row">
<div class="span12" id="ajaxcontainer">
<table class='table table-striped' id='resulttable' >
<thead>
<th>Image</th>
<th>Name</th>
<th>Anime</th>
</thead>
<tbody>
<?php
foreach ($characters as $row) {
echo "<tr class='resulttr'><td><a href='" . base_url('site/character'). '/' . $row->character_id . "' ><image height=140 width=140 src='" . base_url('img/characterimage') . "/" . $row->file_path . "' /></a></td>";
echo "<td>" . $row->character_name . "</td>";
echo "<td>" . $row->anime . "</td>";
echo "<td class='rowid' style='display:none;'>" . $row->character_id . "</td></tr>";
}
?>
</tbody>
</table>
<div class="form-actions">
<?php echo $this->pagination->create_links(); ?>
</div>
</div>
</div>
</div> <!-- /container -->
$config['total_rows'] = $this->db->get('characters')->num_rows();
This is what the Pagination class uses to determine the number of links to create. You're telling it to use every row in the characters table.
You'll need to add your WHERE constraints to this query as well to get the correct number of total records.

Foreach echo without empty variable values

I´d like to use foreach to echo all images-path, but when a variable is empty $bild_5 than shouldn't display any HTML code around.
My code:
<html>
<?php
// var
$url = "http://www.URL/assets/";
$bild_1 = $url . "bild-1.jpg";
$bild_2 = $url . "bild-2.jpg";
$bild_3 = $url . "bild-3.jpg";
$bild_4 = $url . "bild-4.jpg";
$bild_5 = "";
// array
$bilder = array ("$bild_1", "$bild_2", "$bild_3", "$bild_4", "$bild_5");
?>
<ul>
<!-- foreach / Template -->
<?php foreach($bilder as $bild) { ?>
<li><img src="<?php echo $bild; ?>"</li>
<?php } ?>
</ul>
</html>
HTML-OUTPUT
<html>
<ul>
<li><img src="http://www.URL/assets/bild-1.jpg"</li>
<li><img src="http://www.URL/assets/bild-2.jpg"</li>
<li><img src="http://www.URL/assets/bild-2.jpg"</li>
<li><img src="http://www.URL/assets/bild-4.jpg"</li>
<li><img src=""</li> // Don´t display this HTML code; ( $bild_5 = ""; )
</ul>
</html>
Thanks for your help
Ogni
You can use continue to skip
<?php foreach($bilder as $bild) { ?>
<?php if (empty($bild)) continue; ?>
<li><img src="<?php echo $bild; ?>"</li>
<?php } ?>
I would also recommend that you use the alternate syntax for control structures when you mix PHP and HTML. It's easier to read
<?php foreach($bilder as $bild) : ?>
<li><img src="<?php echo $bild; ?>"</li>
<?php endforeach; ?>
Reference - http://php.net/manual/en/control-structures.alternative-syntax.php
Either use continue; as stated above, or simply let array_filter($bilder); run before your foreach

CakePHP - Use JQuery/Ajax to increment an entry in the Db and update a DIV with the result

First all, I am still learning CakePHP and I am close to ZERO using JQuery.
I would like to get help for the following problem I am having:
I have an Articles_Controller a Comments_Controller and Users_Controller
Currently my articles_controller display an article and its comments are loaded on that page
Whoever user inputted the comment will also appear along with his/her image
On each comment I have added a like/dislike button.
Example:
Right now, however, I am only able to display it. What I wanted to accomplish is to use JQuery so that when a user clicks on the Thumbs Up or Thumbs Down image the like and disliked fields are automatically updated in the Db. Also, using JQuery I would like to update those same values in the View. Please my code below and thank you for your help.
articles/view.ctp
<div id="articles_comments">
<p>
Comments
</p>
<?php
foreach($comments as $comment){
?>
<div id="articles_comments_user">
<img src="<?php echo $comment['User']['image']; ?>">
<p>
<?php
$created = $comment['Comment']['created'];
echo $comment['User']['first_name'];
echo " ";
echo $comment['User']['last_name'];
echo " ";
//echo $comment['Comment']['created'];
echo $this->Time->timeAgoInWords(
$comment['Comment']['created'],
array(
'end'=>'+150 years'
)
);
?>
<p>
</div>
<div id="articles_comments_comment">
<table>
<tr>
<td style="width:85%">
<?php echo $comment['Comment']['comment'];?>
</td>
<td style="width:15%;border-left:solid thin teal;">
<div style="float:left;">
<?php echo $comment['Comment']['liked'];?>
<img width="20" src="/img/icons/thumb-up-icon.png"
</div>
<div style="float:right;margin-left:10px;">
<?php echo $comment['Comment']['disliked'];?>
<img width="20" src="/img/icons/thumb-down-icon.png">
</div>
</td>
</tr>
</table>
</div>
<?php
}
?>
<div class="articles_add_comment" id="formUpdateID">
<hr style="width:100%"><br>
<div style="float:left">
<h3>Seu Commentario:</h3>
<?php
echo $form->create(
'Comment',
array(
'url'=>array(
'controller'=>'articles',
'action'=>'view',
$article['Article']['id']
),
'class' => 'articles_form',
'id' => 'loginForm'
)
);
echo $form->input(
'Comment.comment',
array(
'label' => false,
'type' => 'textarea',
'div' => 'articles_comments_textarea',
'cols' => 90,
'rows' => 3
)
);
?>
</div>
<div style="float:right">
<?php
echo $this->Form->submit(
'Send',
array(
'class' => 'articles_comments_button'
)
);
echo $form->end();
?>
</div>
<div class="ajax-save-message">
<?php echo $this->Session->flash(); ?>
</div>
</div>
</div>
Comments is generated from the Articles View action
I was able to fix my problem by the following upon some research and try outs:
View file
<?php foreach $commments as $commment{ ?>
// .............................................................................
<td style="vertical-align:middle;border-left:solid thin teal;padding-left:5px;">
<div class="voteup" style="margin-left:10px;float:left;width:55px;">
<p style="display:none;float:left">
<?php echo $comment['Comment']['id']; ?>
</p>
<div style="float:left" id="article_thumbsUp">
<?php echo $comment['Comment']'liked'];?>
</div>
<img width="20" src="/img/icons/thumb-up-icon.png">
</div>
<div class="votedown" style="float:left;width:55px;">
<p style="display:none;float:left">
<?php echo $comment['Comment']['id']; ?>
</p>
<div style="float:left" id="article_thumbsDown">
<?php echo $comment['Comment']'disliked'];?>
</div>
<img width="20" src="/img/icons/thumb-down-icon.png">
</div>
</td>
// ...............................................................................
<?php } ?>
jQuery I used
<script>
$(document).ready(function(){
$(".voteup").click(function() {
var Id = $(this).children("p").text();
$(this).children("#article_thumbsUp").load("/comments/voteup/"+Id);
});
});
</script>
<script>
$(document).ready(function(){
$(".votedown").click(function() {
var Id = $(this).children("p").text();
$(this).children("#article_thumbsDown").load("/comments/votedown/"+Id);
});
});
</script>
And both of my actions in my comments_controller.php
function voteUp($id = null){
$this->autoRender = false;
if($this->RequestHandler->isAjax()){
$this->Comment->id = $id;
if($this->Comment->saveField('liked',$this->Comment->field('liked')+1)){
}
}
$newValue = $this->Comment->findById($id);
return $newValue['Comment']['liked'];
}
function voteDown($id = null){
$this->autoRender = false;
if($this->RequestHandler->isAjax()){
$this->Comment->id = $id;
if($this->Comment->saveField('disliked',$this->Comment->field('disliked')+1)){
}
}
$newValue = $this->Comment->findById($id);
return $newValue['Comment']['disliked'];
}
This is my entire code in detail and hopefully it can help someone else. This is the way I know how to do, and if you have any better way, I was be glad to know. Thanks a lot. THIS WORKS GREAT. I JUST NEED TO ADD A FEW MORE THINGS TO THIS SYSTEM, SUCH AS ONLY ALLOW REGISTERED USERS TO VOTE AND ONLY ONCE PER COMMENT. THAT WILL INVOLVE CREATING ANOTHER TABLE TO TRACK THAT.
Personally, I would create actions in the Comments_Controller, voteup and votedown. Then, make the thumbs up and thumbs down images link to /comments/voteup/id, etc.
After doing this, use jQuery to prevent a page reload when they're clicked, as such...
<a class="voteup" href="<?php echo $this->base;?>/comments/voteup/<?php echo $comment['Comment']['id'];?>">
<img ... />
</a>
<script>
$(".voteup").click(function(e) {
e.preventDefault();
$.ajax({
url: $(this).attr('href),
success: function() {
// Update vote counter
}
});
});
</script>
I'm sure you can piece together the rest.

Resources