Loop through images not working - php

With this code, the ID is always 1. I want it to add +1 for each times it loops through the messages.
Like ex1, ex2 ex3 etc. etc.
I cant figure it out whats wrong. Could anyone help?
foreach ($message['attachment'] as $attachment)
{
if ($attachment['is_image'])
{
if ($attachment['thumbnail']['has_thumb'])
echo '<img src="', $attachment['thumbnail']['href'], '" alt="" id="thumb_', $attachment['id'], '" border="0" class="opplastetbilde"/><br />';
else
$id = 1;
if ($id < 10) {
echo '<span class="zoom" id="ex' . $id . '"><img src="' . $attachment['href'] . ';image" alt="" width="' . $attachment['width'] . '" height="' . $attachment['height'] . '" border="0" class="opplastetbilde"/></span><br />';
$id++;
}
}
echo '<img src="' . $settings['images_url'] . '/icons/clip.gif" align="middle" alt="*" border="0" /> ' . $attachment['name'] . ' (', $attachment['size'], ($attachment['is_image'] ? ', ' . $attachment['real_width'] . 'x' . $attachment['real_height'] . ' - ' . $txt['attach_viewed'] : ' - ' . $txt['attach_downloaded']) . ' ' . $attachment['downloads'] . ' ' . $txt['attach_times'] . '.)<br />';
}

move this before foreach or it is always reinitialize $id
$id = 1;
foreach ($message['attachment'] as $attachment)
{

Right now, you're setting $id = 1 each time you loop through the array
foreach ($message['attachment'] as $attachment) {
// ...
$id = 1;
// ...
}
In order to increment it properly, you need to place it before the loop
$id = 1;
foreach ($message['attachment'] as $attachment) {
// ...
}

Related

How to get array from API

I want to get the episode number and Released from
http://www.omdbapi.com/?t=the+walking+dead&season=6&r=json
but I don't know how to extract arrays from the api.
Can someone help me?
My code is:
$title = 'the+walking+dead';
$title2 = urlencode($title);
$json=file_get_contents("http://www.omdbapi.com/?t=$title2&season=6&r=json");
$details=json_decode($json);
if($details->Response=='True')
{
$episodios=$details->Episodes;
}
$title = 'the+walking+dead';
$title2 = urlencode($title);
$json = file_get_contents("http://www.omdbapi.com/?t=$title2&season=6&r=json");
$details = json_decode($json);
if ($details->Response == 'True') {
echo 'There are ' . count($details->Episodes) . ' episodes<br />';
foreach ($details->Episodes as $key => $episode) {
echo 'Episode criteria number is ' . ($key + 1) . '<br />';
echo 'Episode Number: ' . $episode->Episode . '<br />';
echo 'Released: ' . $episode->Released . '<br />';
}
}
<?php
$title = 'the+walking+dead';
$title2 = urlencode($title);
$json=file_get_contents("http://www.omdbapi.com/t=$title2&season=6&r=json");
$details=json_decode($json);
if($details->Response=='True')
{
$episodios=$details->Episodes;
foreach ($episodios as $episode) {
echo 'Episode Number: ' . $episode->Episode . '<br />';
echo 'Released Date: ' . $episode->Released . '<br />';
}
}
?>

Show related posts' categories in WordPress

I am trying to also display the category of a related post, below one article.
I am using Newsmag theme.
The code that builds my related posts is this:
class td_module {
var $post;
var $title_attribute;
var $title;
var $href;
var $td_review; //review meta
var $category;
//constructor
function __construct($post) {
//this filter is used by td_unique_posts.php - to add unique posts to the array for the datasource
apply_filters("td_wp_boost_new_module", $post);
$this->post = $post;
$this->title = get_the_title($post->ID);
$this->title_attribute = esc_attr(strip_tags($this->title));
$this->href = esc_url(get_permalink($post->ID));
$this->category = '';
if (has_post_thumbnail($this->post->ID)) {
$this->post_has_thumb = true;
} else {
$this->post_has_thumb = false;
}
//get the review metadata
$this->td_review = get_post_meta($this->post->ID, 'td_review', true);
}
and the part that displays the related articles is this:
$buffy .= '<div class="td-module-thumb">';
if (current_user_can('edit_posts')) {
$buffy .= '<a class="td-admin-edit" href="' . get_edit_post_link($this->post->ID) . '">edit</a>';
}
$buffy .='<a href="' . $this->href . '" rel="bookmark" title="' . $this->title_attribute . '">';
$buffy .= '<img width="' . $td_temp_image_url[1] . '" height="' . $td_temp_image_url[2] . '" itemprop="image" class="entry-thumb" src="' . $td_temp_image_url[0] . '" ' . $attachment_alt . $attachment_title . '/>';
$buffy .= '<span class="td-module-thumb-category">'.$this->category.'</span>';
....................................
$this->category was added by me. I am trying to get the data from wp_terms table and display the categories of each of the related posts.
I am new to WordPress(actually, this is the first time I touch WordPress code).
Thank you
This should work with your existing code:
$buffy .= '<div class="td-module-thumb">';
$related_category = get_the_category($this->post->ID);
if (current_user_can('edit_posts')) {
$buffy .= '<a class="td-admin-edit" href="' . get_edit_post_link($this->post->ID) . '">edit</a>';
}
$buffy .='<a href="' . $this->href . '" rel="bookmark" title="' . $this->title_attribute . '">';
$buffy .= '<img width="' . $td_temp_image_url[1] . '" height="' . $td_temp_image_url[2] . '" itemprop="image" class="entry-thumb" src="' . $td_temp_image_url[0] . '" ' . $attachment_alt . $attachment_title . '/>';
$buffy .= '<span class="td-module-thumb-category">'.$related_category[0]->cat_name.'</span>';
Or if you need the category to be a link use:
$buffy .= '<div class="td-module-thumb">';
$related_category = get_the_category($this->post->ID);
if (current_user_can('edit_posts')) {
$buffy .= '<a class="td-admin-edit" href="' . get_edit_post_link($this->post->ID) . '">edit</a>';
}
$buffy .='<a href="' . $this->href . '" rel="bookmark" title="' . $this->title_attribute . '">';
$buffy .= '<img width="' . $td_temp_image_url[1] . '" height="' . $td_temp_image_url[2] . '" itemprop="image" class="entry-thumb" src="' . $td_temp_image_url[0] . '" ' . $attachment_alt . $attachment_title . '/>';
$buffy .= '<span class="td-module-thumb-category">'.$related_category[0]->cat_name.'</span>';
You will probably want to move $related_category = get_the_category($this->post->ID); to where you have $this->category = ''; in your first pasted code segment

How to count each field in php

I have the below code:
function cat_fields($fields)
{
global $cfg;
$fields['cat_furl'] = str_replace('%cat_safename%', $fields['cat_safename'], $cfg->getVar('urlformat_cat'));
$fields['cat_furl'] = $cfg->getVar('site_url') . str_replace('{cat_safename}', $fields['cat_safename'], $fields['cat_furl']);
$fields['cat_flink'] = '<a id="a' . count($fields) . '" href="' . $fields['cat_furl'] . '" title="' . $fields['cat_title'] . '">' . $fields['cat_name'] . '</a>';
return $fields;
}
And i am trying to count each field of $fields['cat_flink'] = '<a id="a' . count($fields) . '" I tried with id="a' . count($fields) . '" but it's returning the total number of field instead of counting them. How can i count them EACH.
Should be
<a id="a1"....>
<a id="a2"....>
Instead it's echoing me
<a id="15"....>
<a id="15"....>
..... and so on
Please help me on this matter.
You're trying to count all the fields in your array; Quoted from the PHP Manual:
Counts all elements in an array, or something in an object.
To get indices (i.e. the numbers you're looking for), you will have to set a starting number and loop over all your fields until you've got them all, and increment that number everytime your walk through the loop.
Your method however, seems to be for only one iteration, which means you would have to store your number elsewhere. A good way to do this would be adding the number as a parameter to your function:
function cat_fields($fields, $number)
{
global $cfg;
$fields['cat_furl'] = str_replace('%cat_safename%', $fields['cat_safename'], $cfg->getVar('urlformat_cat'));
$fields['cat_furl'] = $cfg->getVar('site_url') . str_replace('{cat_safename}', $fields['cat_safename'], $fields['cat_furl']);
$fields['cat_flink'] = '<a id="a' . $number . '" href="' . $fields['cat_furl'] . '" title="' . $fields['cat_title'] . '">' . $fields['cat_name'] . '</a>';
return $fields;
}
Having done that you should edit the loop (I presume) you're using to call the function multiple times:
for ($i = 1; $i < count($yourArray); $i++) {
// code
$foo = cat_fields($yourArray, $i);
// more code
}
Hope that helps.
EDIT:
I've edited the pastebin from lines 131-141:
if(($rs = $db->execute($sql)) && (!$rs->EOF))
{
$i = 1;
while(!$rs->EOF)
{
$rs->fields = seoscripts_prepare_cat_fields($rs->fields, $i);
$tpl->assign_array_d('tool_category_row', $rs->fields);
$tpl->parse_d('tool_category_row');
$rs->MoveNext();
$i += 1;
}
}
Counting like thatcount($fields) returns the numbers of fields you have you need to add a integer like i=0;
and increase it i++;
Try this
function cat_fields($fields)
{
global $cfg;
$fields['cat_furl'] = str_replace('%cat_safename%', $fields['cat_safename'], $cfg->getVar('urlformat_cat'));
$fields['cat_furl'] = $cfg->getVar('site_url') . str_replace('{cat_safename}', $fields['cat_safename'], $fields['cat_furl']);
$i=0;
foreach($fields as $field)
{
$fields['cat_flink'] = '<a id="a'.$i.'" href="' . $field['cat_furl'] . '" title="' . $field['cat_title'] . '">' . $field['cat_name'] . '</a>';
i++;
}
return $fields;
}
Try this
function cat_fields($fields)
{
global $cfg;
$fields['cat_furl'] = str_replace('%cat_safename%', $fields['cat_safename'], $cfg->getVar('urlformat_cat'));
$fields['cat_furl'] = $cfg->getVar('site_url') . str_replace('{cat_safename}', $fields['cat_safename'], $fields['cat_furl']);
$str = '';
$i = 0;
foreach($fields as $field)
{
$str . = '<a id="a' . $i . '" href="' . $fields['cat_furl'] . '" title="' . $fields['cat_title'] . '">' . $fields['cat_name'] . '</a>';
$i++;
}
$fields['cat_flink'] = $str;
return $fields;
}
if you are counting an array then
echo count($array);
will give the count of every element in the array.

Pagination for my situation?

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/

Last iteration of PHP foreach loop code change

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' : '') . '">';
[...]
}

Categories