PHP: How to use two dimensional array to display menu? - php

I think I'm picking this up pretty well, but I'm just stuck on this. I want to display this menu using an array and foreach loop:
<img src="/img/page-icons/credit-card21.png" />Payments
<a target="_blank" href="/cloud"><img src="/img/page-icons/upload123.png" />Cloud</a>
<a target="_blank" href="/portal"><img src="/img/page-icons/earth208.png" />Portal</a>
So to do that I need to turn that into this line in PHP:
echo '<img src="/img/page-icons/' . $image . '" />' . $title . '';
To fill that out in the loop we need to create something like this... which is where I'm stuck:
foreach( $stamp as $link => $target ){
echo '<a href="/' . $link . '" target="' . $target . '">';
foreach( $stamp[] as $title => $image ){
echo '<img src="/img/page-icons/' . $image . '" />' . $title;
}
echo '</a>';
}
I don't really know how to go about the above, just been messing around with it for a while today. I also don't want to always display target="' . $target . '" on every link.
The array would probably be a two dimensional array? Something like this any way:
$stamp = array(
'link' => array('title' => 'image'),
'link' => array('title' => 'image'),
'link' => array('title' => 'image')
);
EDIT:
There's some confusion of what 'target' is, I want to echo 4 values from an array into a link, target is one of the values. I didn't know how to use that in the array so I just left it out.

When you do:
foreach( $stamp as $link => $target )
The $link variable contains the string "link" and the $target variable is an array such as ['title' => 'image'].
What you should probably do is have an array like this:
// Init links
$links = array();
// Add links
$links[] = array(
'title' => 'My Title',
'href' => 'http://www.google.com',
'target' => '_blank',
'image' => 'image.png',
);
foreach ($links as $link)
{
echo '<a href="'.$link['href'].'" target="'.$link['target'].'">';
echo '<img src="/img/page-icons/' . $link['image'] . '" />';
echo $link['title'];
echo '</a>';
}
This is a bit more flexible approach that lets you add other data items to the structure in the future. That $links array could easily be generated in a loop if you have a different data source such as a database as well.
EDIT
To answer your further question, you can prefix the link building with a set of sane defaults like this:
foreach ($links as $link)
{
// Use the ternary operator to specify a default if empty
$href = empty($link['href']) ? '#' : $link['href'];
$target = empty($link['target']) ? '_self' : $link['target'];
$image = empty($link['image']) ? 'no-icon.png' : $link['image'];
$title = empty($link['title']) ? 'Untitled' : $link['title'];
// Write link
echo "<a href='$href' target='$target'>";
echo "<img src='/img/page-icons/$image' />";
echo $title;
echo "</a>";
}

you can set your array like:
$stamp = array(
'0' => array('title'=>$title 'image'=>$image,'link'=>$link,'target'=>$target),
'1' => array('title'=>$title, 'image'=>$image,'link'=>$link,,'target'=>$target),
'2' => array('title'=>$title 'image'=>$image,'link'=>$link,'target'=>$target)
);
and in foreach you can write
$i=0;
foreach( $stamp as $st=> $target ){
echo '<a href="/' . $st['link'] . '" target="' . $st['target'] . '">';
echo '<img src="/img/page-icons/' . $st['image'] . '" />' . $st['title'];
echo '</a>';
}

Related

How to pass multiple variables in a href?

I tried some code based on similar questions but keep getting error. Based on this similar question I tried:
$step1 = 'my_shop';
$step2 = 'https://my-website.com/';
echo '<a href="' .$step2. .$step1. '">';
Following the logic from this similar question I also tried:
$step1 = 'my_shop';
$step2 = 'https://my-website.com/';
echo '<a href="' .$step2&$step1. '">';
You should use the http_build_query() function, as it was designed for this:
$data = array(
'foo' => 'bar',
'baz' => 'boom',
'cow' => 'milk',
'php' => 'hypertext processor'
);
and then:
$base_url = 'https://my-website.com/';
$query_params = http_build_query($data);
$link = $base_url . '?' . $query_params;
echo 'link text';
Result:
link text

PHP: Next Value in Associative Array [duplicate]

I'm trying to make a gallery using PHP. The images load properly, but the next and previous buttons don't seem to work. Clicking next on picture #1 brings you to picture #3 but clicking back on picture #3 bring you to picture #2 which is correct. How should I change my code to make it so both go in order?
<?php
function listPicturesInDir($dir) {
$dirname = "../pictures/photos/" . $dir . "/";
$images = glob($dirname . "*.jpg");
$previousPic = "null";
foreach ($images as $image) {
$next = next($images);
$name = str_replace(".jpg", "", $image);
$fp = strrpos($name, '/', 5) + 1;
$name = substr($name, $fp, strlen($name));
$id = str_replace(" ", "", $name);
echo '<img class="galleryPics" src="' . $image . '" alt = "' . $name . '" title="'. $name.'"/>';
echo '<div id="' . $id . '" class="modalDialog">';
echo '<div>';
if($previousPic !== "null"){
echo'<img src="../pictures/arrowLeft2.png" alt="Previous photograph" title= "Previous photograph" class="arrow"/> ';
}
if($next !== false){
$name_next = str_replace(".jpg", "", $next);
$fp_next = strrpos($name_next, '/', 5) + 1;
$name_next2 = substr($name_next, $fp_next, strlen($name_next));
$id_next = str_replace(" ", "", $name_next2);
echo'<img src="../pictures/arrowRight2.png" alt="Next photograph" title="Next photograph" class="arrow"/>';
}
echo 'X';
echo '<h2>' . $name . '</h2>';
echo '<img class="modalImg" src="' . $image . '" alt = "' . $name . '"/>';
echo '</div>';
echo '';
echo '</div>';
//echo $next;
$previousPic = $id;
}
}
?>
The problem is that you are using next($images) within a foreach ($images ...) statement, thus modifying the internal array pointer. This may lead to unexpected behavior, as pointed out in the documentation on foreach:
As foreach relies on the internal array pointer, changing it within the loop may lead to unexpected behavior.
This illustrates your problem, using foreach and next:
$images = array('one', 'two', 'three', 'four');
foreach ($images as $image) {
$next = next($images);
echo "$image => $next", PHP_EOL;
}
Output:
one => three
two => four
three =>
four =>
One may think that just replacing the next() with current() would help, but alas:
foreach ($images as $image) {
$next = current($images);
echo "$image => $next", PHP_EOL;
}
Output:
one => two
two => two
three => two
four => two
According to a comment on the foreach documentation page, there used to be a notice on said page stating that:
Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself. foreach has some side effects on the array pointer. Don't rely on the array pointer during or after the foreach without resetting it.
Don't know why that was removed, but if we use a reference for $image then it actually works (note the &):
foreach ($images as &$image) {
$next = current($images);
echo "$image => $next", PHP_EOL;
}
Output:
one => two
two => three
three => four
four =>
But then maybe an old school for loop just makes more sense:
for ($i = 0; $i < count($images); $i++) {
$nextIndex = $i + 1;
$next = ($nextIndex < count($images)) ? $images[$nextIndex] : null;
$image = $images[$i];
echo "$image => $next", PHP_EOL;
}
Output:
one => two
two => three
three => four
four =>
Output from PHP 5.5.20.
$images = sort(glob($dirname . "*.jpg"));

PHP Preg_Match array

I want to remove certain characters in a link. i.e.
'http://www.bbc.co.uk', strip everything and just be left with 'bbd'
At the moment i have the following:
$filteredFeed[$item->get_title()] = array('title' => $item->get_title(), 'permalink' => $item->get_permalink(), 'date' => $item->get_date('G:i d-M-y'),
'url' =>$item->get_link());
}
endforeach;
foreach ($filteredFeed as $items) {
echo '<li class="tips"><a href="' . $items['permalink'] . ' "target="_blank"">';
echo $items['title'];
echo '</a>';
echo ' ';
echo '<span class="date">';
echo $items['date'];
echo '</span>';
echo ' ';
//echo $date;
echo '</li>';
'url' =>$item->get_link()); - i get the link here.
How can i strip out the characters?
$url= 'http://www.bbc.co.uk';
$url = basename($url);
$url = str_replace('www.','',$url);
$url = preg_replace('/\.[^\.].*$/','',$url );
But this match always first subdomain exept www. TThen you may have interest to keep the basename.

PHP Read XML Podcast RSS Feed

OK, so, I'm creating a page for a friend's podcast site that lists out all of the episodes to his podcast(s). Essentially, all I'm looking for is how to read the RSS Feed. Parse out the Nodes, and display the information on the screen. (eventually, I'm going to create a player that will play the episodes, but that's much later)
This is how I'm reading the RSS Feed (which is to one of my shows - for testing purposes).
click to see My Feed
<?php
//Errors:
ini_set('display_errors', 'On');
error_reporting(E_ALL);
$rss = new DOMDocument();
$rss->load('http://tbpc.podbean.com/feed/');
$feed = array();
foreach ($rss->getElementsByTagName('item') as $node) {
$item = array (
'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
'guid' => $node->getElementsByTagName('guid')->item(0)->nodeValue,
'enclosure' => $node->getElementsByTagName('enclosure')->item(0)->nodeValue,
);
array_push($feed, $item);
}
$limit = 1;
for($x=0;$x<$limit;$x++) {
$title = str_replace(' & ', ' & ', $feed[$x]['title']);
$link = $feed[$x]['link'];
$description = $feed[$x]['desc'];
$short = substr($description, 0, strpos( $description, '<'));
$file = $feed[$x]['guid'];
echo '<p><strong>'.$title.'</strong></p>';
echo '<p>'.$description.'</p>';
echo '<p>'.$short.'</p>';
echo '<p>'.$file.'</p>';
}
?>
The problem is - is that I have no idea how to get the information out of the attribute url of the enclosure node so I can display it on the page with the rest of the information (this will come in handy when I make the player - eventually).
SO! How do I get the url attribute from the enclosure node? Am I going about this all wrong?
Any helpful hints would be appreciated. Thanks.
Apologies if you're determined to use DOMDocument() in this, but since nobody has posted an answer so far...here's a script which uses simple_xml_load_file(), which I found quite easy to get to grips with.
<?php
$rss_array = array('http://rss.computerworld.com/computerworld/s/feed/topic/231', 'http://rss.computerworld.com/computerworld/s/feed/topic/230', 'http://rss.computerworld.com/computerworld/s/feed/topic/66', 'http://www.engadget.com/rss.xml', 'http://feeds.webservice.techradar.com/rss/new', 'http://feeds.arstechnica.com/arstechnica/index', 'http://www.notebookcheck.net/News.152.100.html', 'http://electronista.feedsportal.com/c/34342/f/626172/index.rss', 'http://www.anandtech.com/rss/pipeline/', 'http://www.digitimes.com/rss/daily.xml', 'http://feeds.feedburner.com/TechCrunch/', 'http://feeds2.feedburner.com/ziffdavis/pcmag/breakingnews', 'http://feeds.feedburner.com/Liliputing', 'http://feeds.slashgear.com/slashgear', 'http://feeds.feedburner.com/GizmagEmergingTechnologyMagazine', 'http://www.zdnet.com/news/rss.xml', 'http://feeds.feedburner.com/mobilityupdate', 'http://www.techmeme.com/feed.xml', 'http://www.notebookreview.com/rss.xml');
for ($i=0; $i<count($rss_array); $i++ ) {
$rssfeed = simplexml_load_file($rss_array[$i]);
foreach ($rssfeed->channel as $channel) {
echo '<h1>' . htmlentities($channel->title) . '</h1>';
echo '<p>' . htmlentities($channel->description) . '</p>';
echo '<p><a href="' . htmlentities($channel->link) . '">' .
htmlentities($channel->link) . '</a></p>';
echo '<input type="button" value=" >>> " onClick="downloadFileViaAjax(\'' . htmlentities($channel->link) . '\')">';
echo '<ul>';
foreach ($channel->item as $item) {
echo '<li><a href="' . htmlentities($item->link) . '">';
echo htmlentities($item->title) . '</a>';
// echo htmlentities($item->description) . '</li>';
echo '<input type="button" value=" >>> " onClick="downloadFileViaAjax(\'' . htmlentities($item->link) . '\')"></li>';
}
echo '</ul>';
}
}//fur ( $rss_array++ )
?>
Nodes have an getAttribute() method. So you can use:
$node->getElementsByTagName('enclosure')->item(0)->getAttribute('url')
But here is another and more comfortable way to fetch nodes and values from an XML DOM: Use Xpath. See this answer: https://stackoverflow.com/a/20225186/2265374
The $node->getElementsByTagName('enclosure')->item(0) will result in an error if no element is found (same goes for SimpleXML btw). If the node list is cast to string in Xpath, the result is just an empty string and no error is triggered.
You can directly fetch attributes this way, too. Like the url attribute of the enclosure element:
echo 'Enclosure Url: ', $xpath->evaluate('string(enclosure/#url)', $rssItem), "\n";

str_replace count occurrences of $placeholder, replace with corresponding $variable

I've been trying to accomplish this for a few days. I have a description in each post that has placeholders manually placed where I want the corresponding image to be replaced. For example:
This is the description shortened...
[image]
[image]
Description starts again with a new paragraph continuing...
The placeholders are [image]. With every new post I upload multiple images, but each post may vary from 1-10 images, so a variable amount of [image] placeholders are placed. I have a function that gets all related images to that post and count how many images there are.
Here is the code I have so far, but what's wrong is, for the first two placeholders [image] it shows the first related image twice, then loops and shows the description again, this time with the second image replacing both [image] placeholders.
<?php
foreach ($photos as $picture) {
$count = count($picture);
for($i = 1; $i<= $count; $i++) {
$image = $picture['filename'];
$replace = "[image]";
$image_path = '../../content_management/image_upload/';
$placeholders = array("$replace");
$image_location = array('<a class="fancybox" href="' . $image_path . '' . $image . '" data-fancybox-group="gallery"><img src="' . $image_path . '' . $image . '" /></a>');
$rawstring = $photo_article['description'];
$new_string = $rawstring;
$new_string = str_replace($placeholders, $image_location, $new_string, $i);
echo $new_string;
}
}
?>
And what the output is:
This is the description shortened...
Image1.jpg
Image1.jpg
Description starts again with a new paragraph continuing...
This is the description shortened...
Image2.jpg
Image2.jpg
Description starts again with a new paragraph continuing...
$photos = array(
'photo1' => array(
'filename' => 'image1.png'
),
'photo2' => array(
'filename' => 'image2.png'
),
);
$photo_article['description'] = "This is the description shortened...
[image]
[image]";
foreach ($photos as $picture)
{
$image = $picture['filename'];
$image_path = '../../content_management/image_upload/';
$replacement = '<a class="fancybox" href="' . $image_path . '' . $image . '" data-fancybox-group="gallery"><img src="' . $image_path . '' . $image . '" /></a>';
$photo_article['description'] = preg_replace("~\[image\]~s", $replacement, $photo_article['description'], 1);
}
echo $photo_article['description'];
you're looping but calling the same $picture['filename'] it should be $picture[$i]['filename'] or just foreach ($picture as $thisPic) { $thisPic['filename']; }

Categories