I have a pretty complicated script that doesn't fully work with MySQL, it does partially though. Let me try to explain...
The results of my page are purely image names from a specific folder, means I use this function to get my results:
function get_all_images($dir)
{
$dir = opendir($dir);
$dirArray = array();
while($entryName = readdir($dir))
{
if(($entryName != ".") && ($entryName != "..") && ($entryName != ".svn") && ($entryName != ".htaccess"))
{
$dirArray[] = $entryName;
}
}
closedir($dir);
(sizeof($dirArray)) ? arsort($dirArray) : '';
return (is_array($dirArray)) ? $dirArray : '';
}
This is how I basically get results in my page:
<?php
include('includes/header.php');
$images = get_all_images('i');
$url = str_replace('www.', '', generate_site_url());
$flag = false;
$count = 0;
if (empty($images))
{
echo '<h2>There are no uploaded images</h2><br>';
}
foreach ($images as $image)
{
$filename = $image_name = $image;
$image_link = $url . IMAGES_PATH . $filename;
$user_id = fetch_user_id($image_link);
$delete_link = (isset($_POST['delete_link'])) ? $_POST['delete_link'] : '';
$delete_image = (isset($_POST['delete_image'])) ? $_POST['delete_image'] : '';
if ($delete_admin_submit)
{
unlink('./t/' . $delete_image);
unlink('./t/big' . $delete_image);
adminDelete('./i/' . $delete_image, $delete_link);
header('Location: ' . $imgit_action);
exit();
}
echo '<div class="' . ($count++ % 2 ? "odd-color" : "even-color") . '">';
echo '<table>';
echo '<tr><td class="fullwidth"><a class="preview_img" href="' . $image_link . '"><img src="' . $image_link . '" title="Click to enlarge" width="300" class="thumb" /></a></td></tr>';
echo '<tr><td><span class="default">Direct link:</span> ';
echo '<input type="text" readonly="readonly" class="link-area" onmouseover="this.select();" value="' . $image_link . '" />';
echo '<form method="post" action="" onsubmit="return confirmSingleDeletion();" style="display: inline;"> ';
echo '<input type="submit" class="icon_delete" name="delete_link" value="' . $image_link . '" title="Delete this image" />';
echo '<input type="hidden" name="delete_image" value="' . $image_name . '" />';
echo '</form>';
echo '</td></tr>';
echo ($flag) ? '<hr /><br>' : '';
echo '</table>';
if (!empty($user_id))
{
echo '<br><strong class="normal">Uploader ID:</strong> ';
echo '<em class="normal">' . $user_id . '</em><br>';
}
echo '<br>';
$flag = true;
}
?>
<span class="button-sub">« Back to Index</span>
<?php echo '</div>'; ?>
<?php include('includes/footer_alt.php'); ?>
Now I have not ANY simple clue how to start breaking my results into pages. I'm working here with over 12000 results and it takes a lot for the page to load, I need help to break this big result into pages.
Anyone willing to help me? At least give me a clue how to start? I would be really grateful.
Thanks a lot for reading.
Consider your array as you collect up the file names but after you have sorted them:
$imgs = array(
0 => 'image1.jpg',
1 => 'image2.jpg',
2 => 'image3.jpg',
3 => 'image4.jpg',
4 => 'image5.jpg',
5 => 'image6.jpg',
6 => 'image7.jpg',
7 => 'image8.jpg',
);
// create some vars which you can use in your pagination
$perpage = 3 ;
$page=2;
$range_end = ($perpage*$page)-1;
$range_start = ($perpage*($page-1));
$display=range($range_start,$range_end);
// loop through results
foreach($display as $show){
echo $imgs[$show];
}
Does that get you a start?
Thanks for trying to answer me Cups and Umair Khan, but I found the working solution here:
http://tiffanybbrown.com/2008/12/14/simple-pagination-for-arrays-with-php-5/
Related
How to add in this code multiple ID category.
I have in kategorija_id 5 arrays:
1 - News
2 - Magazine
3 - Kokursi
4 - Grantovi ect..
I whant to display just key 1 and 2
when i add array i just print the first key
$kategorija = Kategorija::model()->findByPk($item->kategorija_**id=1,2**);
Thnx :)
Code update:
<div class="carousel-inner">
<div class="item active">
<ul class="thumbnails">
<?php
$i = 0;
$lastDefault = 0;
foreach ($ids as $itemId) {
$item = InfoPaket::model()->findByPk($itemId);
$kategorija = Kategorija::model()->findByPk($item->kategorija_id);
if ( $i % 3 == 0 && $i > 0 ) {
echo "</ul></div><div class='item'><ul class='thumbnails'>";
}
$imageUrl = $_SERVER['DOCUMENT_ROOT'] . Yii::app()->baseUrl . "/images/infopaket/" . $item->slika;
if ( !file_exists($imageUrl) || empty($item->slika)) {
if ( $lastDefault == 0 ) {
$imagePath = Yii::app()->baseUrl . "/images/infopaket/info_paket.png";
$lastDefault = 1;
} else {
$imagePath = Yii::app()->baseUrl . "/images/infopaket/info_paket_redv2.png";
$lastDefault = 0;
}
} else {
$imagePath = Yii::app()->baseUrl . "/images/infopaket/" . $item->slika;
}
echo "<li class='span3 thmb-elem'>";
echo "<div class='thumbnail right-caption image'>";
echo "<a class='img-link' href='" . Yii::app()->getHomeUrl() . "?r=infoPaket/clanak&id=" . $item->id . "'><img class='img-class' src='$imagePath'></a>";
echo "</div>";
echo "<div class='caption caption-link'>";
echo "<div class='naziv'><img class='arrow-img' src='". Yii::app()->getBaseUrl() . "/themes/shadow_dancer/images/arrow.png'> " . strtoupper($kategorija->naziv) . "</div>";
echo "<p><a class='naslov' href='" . Yii::app()->getHomeUrl() . "?r=infoPaket/clanak&id=" . $item->id . "'><strong>" . $item->naslov . "</strong></a></p>";
echo "</div>";
echo "</li>";
$i++;
}
?>
</ul>
</div>
</div>
I solve this problem adding this line of code
if ($item->kategorija_id==3 || $item->kategorija_id==4 ) {
now code look like this and it works perfect.
<?php
$lastDefault = 0;
foreach ($ids as $itemId) {
$item = InfoPaket::model()->findByPk($itemId);
$kategorija = Kategorija::model()->findByPk($item->kategorija_id);
if ($item->kategorija_id==3 || $item->kategorija_id==4 ) {
echo '<li>';
echo '<img src="<?php echo Yii::app()->theme->baseUrl; ?>/images/infopaket/info_paket.png" />';
echo '<h2>';
echo strtoupper($kategorija->naziv);
echo '</h2>';
echo '<h1>';
echo "<a class='naslov' href='" . Yii::app()->getHomeUrl() . "?r=infoPaket/clanak&id=" . $item->id . "'>";
echo $item->naslov;
echo '</h1>';
echo '</a>';
echo '</li>';
}
}
?>
findByPk() accepts first argument as array too. So you can do
category::model()->findByPk(array('1', '2'));
Also, $item->category_id will return only single entry. If your item has multiple categories, than set up relations to categories and then get categories ID's with
CHtml::listData($item->categoriesRelationName, 'id', 'id');
can use function ($data){return $data->attribtues} too ---------^--- to get all attributes of model
I'm using a script PHP to get all posts from a fan page. The code is this:
require_once("../facebook-sdk/src/facebook.php");
$config = array(
'appId' => '#############',
'secret' => '###############################',
'fileUpload' => false
);
$facebook = new Facebook($config);
$facebook->setAccessToken("###################################");
$pageid = "###############";
$pagefeed = $facebook->api("/" . $pageid . "/feed");
$i = 0;
foreach($pagefeed['data'] as $post) {
if ($post['type'] == 'video' || $post['type'] == 'link' || $post['type'] == 'photo') {
// open up an fb-update div
echo "<div class=\"fb-update\">";
// check if post type is a link
if ($post['type'] == 'link') {
echo '<img class="imagem-feed" src="' . $post["picture"] . '">';
$interno = "<p>" . $post['message'] . "</p><p>" . $post['link'] . "</p>";
}
// check if post type is a photo
if ($post['type'] == 'photo') {
$fotoAlta = $facebook->api("/" . $post["object_id"] . "?fields=source");
echo '<img class="imagem-feed" src="' . $fotoAlta["source"] . '">';
//interno
if (empty($post['story']) === false) {
$interno = "<p>" . $post['story'] . "</p>";
} elseif (empty($post['message']) === false) {
$interno = "<p>" . $post['message'] . "</p>";
}
$interno .= "<p>Ver no Facebook →</p>";
}
// check if post type is a video
if ($post['type'] == 'video') {
echo '<iframe class="imagem-feed" width="350" height="263" src="' . str_replace("&autoplay=1","",$post["source"]) . '" frameborder="0" allowfullscreen></iframe>';
//interno
if (empty($post['story']) === false) {
$interno = "<p>" . $post['story'] . "</p>";
} elseif (empty($post['message']) === false) {
$interno = "<p>" . $post['message'] . "</p>";
}
}
echo '<div class="cabecalho-fanpage"><a target="_blank" href="https://www.facebook.com/Angelameza.arquitetura"><img class="img-perfil-fanpage" width="50" height="50" src="http://profile.ak.fbcdn.net/hprofile-ak-ash1/373040_201176906637605_665931623_q.jpg"><h1>' . $post["from"]["name"] . '</h1><p>' . date("d/m/Y", (strtotime($post['created_time']))) . '</p></a></div>';
echo $interno;
echo '<div class="container-interacoes">';
$totalCurtidas = $facebook->api("/" . $post["id"] . "/likes/?summary=true");
$titulo = ($totalCurtidas["summary"]["total_count"] == 0 || $totalCurtidas["summary"]["total_count"] > 1) ? $totalCurtidas["summary"]["total_count"] . " pessoas curtiram isso." : "1 pessoa curtiu isso.";
echo "<span title='$titulo' class='icon-curtidas'>" . $totalCurtidas["summary"]["total_count"] . "</span>";
$compartilhamentos = (isset($post["shares"]["count"])) ? $post["shares"]["count"] : 0;
$titulo = ($compartilhamentos == 0 || $compartilhamentos > 1) ? $compartilhamentos . " pessoas compartilharam isso." : "1 pessoa compartilhou isso.";
echo "<span title='$titulo' class='icon-compartilhamentos'>" . $compartilhamentos . "</span>";
$totalComentarios = $facebook->api("/" . $post["id"] . "/comments/?summary=true");
$titulo = ($totalComentarios["summary"]["total_count"] == 0 || $totalComentarios["summary"]["total_count"] > 1) ? $totalComentarios["summary"]["total_count"] . " pessoas comentaram isso." : "1 pessoa comentou isso.";
echo "<span title='$titulo' class='icon-comentarios'>" . $totalComentarios["summary"]["total_count"] . "</span>";
echo "</div>";
echo "<div style='clear:both'></div></div>"; // close fb-update div
$i++; // add 1 to the counter if our condition for $post['type'] is met
}
} // end the foreach statement
Using this code, the page is very slow (50 seconds to load). I tested any thing for optimize and don't improve. Can someone help me?
You are making calls to graph API inside the for loop, i.e for every post, you are making additional calls. Obviously, this contributes towards your 50 secs. Your best bet is to arrange your code to use batch requests. Here is the documentation for batching calls.
https://developers.facebook.com/docs/graph-api/making-multiple-requests/
Note: You can make upto 50 calls in one go using a batch request.
I want a gallery of uploaded images, showing 4 images each tr.
There needs to be a loop somewhere but I can't get it to work.
It needs to add a tr automatically when there are 4 images in a tr.
<?php
$folder = 'uploads/';
$filetype = '*.*';
$files = glob($folder.$filetype);
$count = count($files);
$sortedArray = array();
for ($i = 0; $i < $count; $i++) {
$sortedArray[date ('YmdHis', filemtime($files[$i]))] = $files[$i];
}
krsort($sortedArray);
echo '<table>';
foreach ($sortedArray as &$filename) {
echo '<td align="center">';
echo '<a name="'.$filename.'" href="#'.$filename.'"><img src="'.$filename.'" /></a>';
echo 'Bestand naam: ' . substr($filename,strlen($folder),strpos($filename, '.')-strlen($folder));
echo '</td>';
}
echo '</table>';
?>
Let a counter, say $i run alongside your foreach loop that ticks up by one every time the loop ran. Check for "every fourth element" with if ($i % 4 ==0)
Use a counter in your loop. It should look like this :
echo '<table>';
$ctr = 0;
foreach ($sortedArray as &$filename) {
echo ($ctr % 4 == 0) ? "<tr>" : "";
echo '<td align="center">';
echo '<a name="'.$filename.'" href="#'.$filename.'"><img src="'.$filename.'" /></a>';
echo 'Bestand naam: ' . substr($filename,strlen($folder),strpos($filename, '.')-strlen($folder));
echo '</td>';
$ctr++;
echo ($ctr % 4 == 0) ? "</tr>" : "";
}
echo '</table>';
<?php
$folder = 'uploads/';
$filetype = '*.*';
$files = glob($folder . $filetype);
$count = count($files);
$sortedArray = array();
$i = 0;
krsort($sortedArray);
echo '<table><tr>';
foreach($sortedArray as & $filename)
{
echo '<td align="center">';
echo '<a name="' . $filename . '" href="#' . $filename . '"><img src="' . $filename . '"/> </a>';
echo 'Bestand naam: ' . substr($filename, strlen($folder) , strpos($filename, '.') - strlen($folder));
echo '</td>';
if ($i % 4 == 0)
{
echo '</tr><tr>';
}
$i++;
}
echo '</tr></table>';
?>
I have a block of PHP code that looks like this:
$flag = false;
if (empty($links))
{
echo '<h1>You have no uploaded images</h1><br />';
}
foreach ($links as $link)
{
$extension = substr($link, -3);
$image_name = ($extension == 'peg') ? substr($link, -15) : substr($link, -14);
($delete_submit) ? deleteImage('.' . $image_name, $link) : '';
echo '<div>';
echo '<table>';
echo '<tr><td class="fullwidth"><a class="preview_img" href="' . $link . '"><img src="' . $link . '" title="Click to enlarge" width="300" class="thumb" /></a></td></tr>';
echo '<tr><td><span class="default">Direct:</span> ';
echo '<input type="text" readonly="readonly" class="link-area" onmouseover="this.select();" value="' . $link . '" />';
echo '</td></tr>';
echo ($flag) ? '<hr /><br>' : '';
echo '</table>';
echo '<br>';
echo '</div>';
$flag = true;
}
I want the <div> to include a different class based on if it is even or odd. If it is even, it gets X class, if it's odd it gets Y class.
How do I do this in my case? I'm totally clueless and I don't know how to start!
Initialise a variable $count=0; before the loop. Then place the following in the loop: ++$count%2?"odd":"even".
$count = 0;
foreach ($links as $link)
{
$extension = substr($link, -3);
$image_name = ($extension == 'peg') ? substr($link, -15) : substr($link, -14);
($delete_submit) ? deleteImage('.' . $image_name, $link) : '';
echo '<div class="' . (++$count%2 ? "odd" : "even") . '">';
[...]
$i++;
echo '<div class="'.($i%2 ? 'odd':'even').'>';
[...]
before the foreach, declare a boolean:
$div_flag = false;
in the foreach, where you echo the div add this:
"class=".( $div_flag ? "'odd'" : "'even'" )
at the end of the foreach (or anywhere in it, really) add this:
$div_flag = !$div_flag;
If you're working on a prototype site, you could always implement a pure CSS solution:
div:nth-child(even) { /* Apply even class rules here */ }
div:nth-child(odd) { /* Apply odd class rules here */ }
The reason I recommend that you only use this for prototype sites is because the compatibility for :nth-child does not support IE8 or below.
Try something like this
$count = 0;
foreach($links as link) {
$count++;
print ($count % 2 == 1) ? "odd" : "even";
}
If you are using a modern browser, you can use CSS with something like this in your style sheet.
div:nth-child(odd)
{
background:#ff0000;
}
div:nth-child(even)
{
background:#0000ff;
}
Add a variable for your loop.
$c = true;
foreach ($links as $link)
{
$extension = substr($link, -3);
$image_name = ($extension == 'peg') ? substr($link, -15) : substr($link, -14);
($delete_submit) ? deleteImage('.' . $image_name, $link) : '';
echo '<div'.(($c = !$c)?' class="odd"':'').">
//echo '<div>';
echo '<table>';
echo '<tr><td class="fullwidth"><a class="preview_img" href="' . $link . '"><img src="' . $link . '" title="Click to enlarge" width="300" class="thumb" /></a></td></tr>';
echo '<tr><td><span class="default">Direct:</span> ';
echo '<input type="text" readonly="readonly" class="link-area" onmouseover="this.select();" value="' . $link . '" />';
echo '</td></tr>';
echo ($flag) ? '<hr /><br>' : '';
echo '</table>';
echo '<br>';
echo '</div>';
$flag = true;
}
Without counters:
<?php $toggle_class = 'even';?>
<?php foreach ($links as $link):?>
<?php $toggle_class = ($toggle_class == 'odd' ? 'even' : 'odd');?>
<div class="<?php echo $toggle_class;?>">
Your div content...
</div>
<?php endforeach;?>
This is the easy tricks
function check_odd_even($data){
if($data % 2 == 0){
$data = "Even";
}
else{
$data = "Odd";
}
return $data;
}
if (check_odd_even($index) == 'Odd'){
//layout 1....
}else{
//layout 2....
}
I have a block of code thats working perfectly to pull data about different office locations.
What I would like to do is be able to make the last iteration of this loop change the div class to something else so I can apply a different set of css styles.
$fields = get_group('Offices');
foreach($fields as $field){
echo'<div class="oloc">';
if($locationVar==NULL || $locationVar!=$field['office-location'][1]) {
echo '<a name="' . strtolower(str_replace(' ', '-', $field['office-location'][1])) . '"></a><h3>' . $field['office-location'][1] . '</h3>';
$locationVar = $field['office-location'][1];
} else {
echo "<br />";
}
if($field['office-gm'][1]){
echo '<div class="gm"><img src="http://maps.googleapis.com/maps/api/staticmap?center=' . $field['office-gm'][1] . '&zoom=9&size=250x250&markers=color:blue|label:A|' . $field['office-gm'][1] . '&sensor=false"></div>';
}
if($field['office-name'][1]){
echo '<strong>' . $field['office-name'][1] . '</strong><br /><br />';
}
if($field['office-phone'][1]){
echo 'Phone: ' . $field['office-phone'][1] . '<br />';
}
if($field['office-fax'][1]){
echo 'Fax: ' . $field['office-fax'][1] . '<br />';
}
if($field['office-address'][1]){
echo '<br />Address:<br />' . strip_tags($field['office-address'][1], '<br><br />') . '<br />';
}
if($field['office-webpage'][1]){
echo 'Web: ' . 'Office Webpage<br />';
}
if($field['office-email'][1]){
echo 'Email: ' . 'Office Email<br />';
}
if($field['office-emp'][1]){
echo 'Jobs: ' . 'Employment Application<br />';
}
if($field['office-fb'][1]){
echo 'Facebook: ' . 'Facebook<br />';
}
if($field['office_office_twitter'][1]){
echo 'Twitter: ' . 'Twitter<br />';
}
echo '</div>';
}
For cases like these you can use a CachingIterator and the hasNext() method:
$fields = get_group('Offices');
$it = new CachingIterator(new ArrayIterator($fields));
foreach($it as $field)
{
...
if (!$it->hasNext()) echo 'Last:';
...
}
Put every echo in a var, this class definition in a other var. Then at the end of your foreach you check like so:
$i = 0;
foreach(...
if( $i == count($fields) ) { // change class }
Try this
$i = 0;
$total = count($fields);
$final = false;
foreach($fields as $field){
$i++;
$final = ($i + 1 == $total)? true : false;
if($final)
echo'<div class="NEW_CLASS">';
else
echo'<div class="oloc">';
....
}
First you should get the total count of the offices so that when you are on the last iteration, you can do something about it.
$fields = get_group('Offices');
$fields_count = count($fields);
$i = 0;
foreach ($fields as $field) {
$is_final = ++$i == $fields_count;
echo '<div class="oloc' . ($is_final ? ' oloc-final' : '') . '">';
[...]
}