Understanding ask - group Indexes together in foreach loop - php

To be short - the code works.
But how ?
I made a PHP curl so scrape a website and get some events. Works.
Then i wanted to group some scraped events together. Tested some variations and to the end i did this:
$communities[$current_color][] = $li->plaintext;
Works. But i cant imagine how this is a grouping function....
Anyone an idea?
Here is the most important of my code:
echo '<article class="month">';
foreach( $html->find('tr') as $tr ){
$montName = $tr->find('.ev_td_left', 0);
echo '<h3>' . $montName->plaintext . '</h3>';
echo '<ul>';
foreach( $tr->find('li') as $li ){
$style = $li->style;
preg_match( "/#.{6}/", $style, $li_bgcolor );
/**
* Array nach Farben gruppieren
*/
$current_color = $li_bgcolor[0];
$communities[$current_color][] = $li->plaintext;
echo '<li><span class="event" style="background-color:'.$li_bgcolor[0].';"></span>'.$li->plaintext.'</li>';
}
echo '</ul>';
echo '<br/>';
}
echo '</article>';

Related

Count loops in foreach and act based on that

Hi i have a function in PHP, which returns colors of my products in woocommerce.
My function:
global $product;
if ( $product->is_type('variable') ) {
$taxonomy = 'pa_color';
$colors = explode(',',$product->get_attribute($taxonomy));
echo '<div class="colour-swatch">';
foreach ($colors as $color) {
echo '<div class="swatch '. strtolower(trim($color)) .'">';
echo '<div class="circle">';
echo '<div style="background-color: var(--'. strtolower(trim($color)) .');"></div>';
echo '';
echo '</div>';
echo '</div>';
}
echo '</div>';
}
What i need is make it count how many colors it finds inside the loop (so how many times the loop is done). And echo it below.
So if one loop is done, it should (echo "1 color").
If 2 or more colors is found it should echo "x colors" (so include the s on color to make it correct).
// To print the total size of the colors.(the number of times the loop ran)
$sz = sizeof($colors);
echo $sz . (($sz==1) ? " color" : " colors");

Traverse an array or cross an array

I am fairly new to php and trying to get echo "<p>" .get_the_tags($author_post). "</p>"; to echo out the tags associated with the post its listing in the loop.
I was told to "you need to traverse the array" and "This returns an array of tags. Then you have to cross the array if you want to echo it out."
but was not told how to accomplish this. I am unsure how to proceed.
Here is the full code.
if ($author_posts) {
echo '<ul>';
$i = 0;
foreach ($author_posts as $author_post) {
/* excluded categories */
if (has_category(explode(',', $atts['exclude']), $author_post->ID)) :
continue;
endif;
$postdate = date_i18n( get_option( 'date_format' ), strtotime($author_post->post_date)).' - ';
echo '<li>';
echo ($atts['postdate'] ? $postdate : ''). ''.$author_post->post_title.'';
$categories = get_the_category( $author_post->ID );
$list_cats =null;
foreach ($categories as $cat) :
$list_cats .= $cat->name.", ";
endforeach;
$list_cats = substr($list_cats, 0, -2);
echo "<p>" .get_the_tags($author_post). "</p>";
echo '</li>';
$i++;
if ($atts['postsperauthor'] > -1) :
if ($i >= $atts['postsperauthor']) :
break;
endif;
endif;
}
}
Thanks for any help you can provide
I guess your get_the_tags() return an array
try this:
$tags = get_the_tags($author_post);
$tagNames = [];
foreach ( $tags as $tag ) {
$tagNames[] = $tag->name
}
echo implode(',',$tagNames)
echo '</div>';
echo '</li>';
BTW , this syntax is a bit old...

How do i display list items from php array

Ive been trying make this display as html list items it just a string that i explode then loop over each item i cant get it to out put correctly. Could some one please show me where im going wrong or suggest an new approch.
this is what ive tried
$path = "1/2/3/4";
$expath = explode("/",$path);
$ret = '';
echo '<ul>';
foreach ($expath as $pitem) {
echo '<li><a href='.$ret .= $pitem. "/".'>'.$pitem.'</a></li>';
}
echo '</ul>';
.
Desired out put on hrefs
1
1/2
1/2/3
1/2/3/4
Desired visual out LIs
1
2
3
4
Output i get be warned
1
12/>212/>23/>312/>23/>34/>4
$path = "1/2/3/4";
$expath = explode("/", $path);
echo '<ul>';
foreach ($expath as $i => $pitem) {
$slice = array_slice($expath, 0, $i + 1);
$path = implode('/', $slice);
echo '<li>' . $pitem . '</li>';
}
echo '</ul>';
$list = explode("/", "1/2/3/4");
This will create an array $list as:
echo $list[0]; // 1
echo $list[1]; // 2
echo $list[2]; // 3
echo $list[3]; // 4
This line is the problem: echo '<li><a href='.$ret .= $pitem. "/".'>'.$pitem.'</a></li>';
Should be formatted like:
echo "<li><a href='{$ret}={$pitem}/'>{$pitem}</a></li>";
or echo '<li>'.$pitem.'</li>';
Its because your $ret. Place that inside the loop. In your code you concatenate $pitem with $ret all older $ret values also get concat.
Try
<?php
$path = "1/2/3/4";
$expath = explode("/",$path);
echo '<ul>';
foreach ($expath as $pitem) {
$ret = '';
echo '<li><a href='.$ret .= $pitem. "/".'>'.$pitem.'</a></li>';
}
echo '</ul>';
If you want = sign tobe there in the url then just change echo by following
echo "<li><a href='$ret=$pitem/'>$pitem</a></li>";
PHP echo with double quotes will print variable value.

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";

Group PHP arrays by key value

Basically I'm trying to group my arrays like this:
Shopping
Amazon
Social
Amoeblo
American express
By using below PHP code:
<?php
echo '<ul id="list"><h2 class="searchresults"></h2>';
foreach($records as $catval) {
$sitechar = $catval->site_category;
echo '<h3 id="disappear">'. strtoupper($sitechar) .'</h3>';
echo '<li class="siteli"><a href="#" class="add">';
echo '<p id="text-site">'.$catval->site_name. '</p></a>';
echo '</li>';
}
echo '</ul>';
?>
But I'm getting values only like below.
Shopping
Amazon
Social
Amoeblo
Social
American express
I'm not getting the exact PHP sorting to use for this.
I would create a new array with categories as keys for arrays with the sites.
<?php
$arr = array();
// First create multidimensional array with categories as keys for site arrays
foreach($records as $catval) {
$sitechar = $catval->site_category;
if (!array_key_exists($sitechar, $arr)) {
// Set new array for a category if it does not exist
$arr[$sitechar] = array();
}
// Add site to category
$arr[$sitechar][] = array(
"name"=>$catval->site_name,
"image"=>$catval->site_img
);
}
// Then iterate the new array of categories
echo ("<ul>");
foreach($arr as $category => $sites) {
echo("<h3>" . $site_category "</h3>");
// Iterate array of sites
foreach($sites as $site) {
echo("<li>" . $site["name"] . "-" , $site["image"] . "</li>");
}
}
echo("</ul>");
?>
You can do it using a foreach and ksort
Let $your_array be the array you mentioned above
$res_array = array();
foreach($your_array as $val){
$res_array[$val->site_category][] = $val->site_name;
}
ksort($res_array);
print_r($res_array);
OR search for multisort in php which will solve your problem :)
$tmp = null;
echo '<ul id="list"><h2 class="searchresults"></h2>';
foreach($records as $catval) {
$myHtml = makeHtml($catval,$tmp);
echo $myHtml;
$tmp = $catval->site_category;
}
echo '</ul>';
function makeHtml($catval,$tmp){
if($tmp != $catval->site_category){ $html .= '<h3 id="disappear">'. strtoupper($catval->site_category) .'</h3>';}
$html .='<li class="siteli"><p id="text-site">'.$catval->site_name. '</p></li>';
return $html;
}

Categories