I have a simplepie feed that spits out multiple feeds from each of the URL's that are loaded into a a associative array.
This associative array is used to sort the arrays alphabetically using the values.
I'm trying to use that same value sort and keep all of the arrays with the same URL or value together so that when the foreach loop runs I get one div per URL containning all the feeds from that URL for the day
<?php
require_once('php/autoloader.php');
$feed = new SimplePie(); // Create a new instance of SimplePie
// Load the feeds
$urls = array(
'http://abcfamily.go.com/service/feed?id=774372' => 'abc',
'http://animal.discovery.com/news/news.rss' => 'animalplanet',
'http://www.insideaolvideo.com/rss.xml' => 'aolvideo',
'http://feeds.bbci.co.uk/news/world/rss.xml' => 'bbcwn',
'http://www.bing.com' => 'bing',
'http://www.bravotv.com' => 'bravo',
'http://www.cartoonnetwork.com' => 'cartoonnetwork',
'http://feeds.cbsnews.com/CBSNewsMain?format=xml' => 'cbsnews',
'http://www.clicker.com/' => 'clicker',
'http://feeds.feedburner.com/cnet/NnTv?tag=contentBody.1' => 'cnet',
'http://www.comedycentral.com/' => 'comedycentral',
'http://www.crackle.com/' => 'crackle',
'http://www.cwtv.com/feed/episodes/xml' => 'cw',
'http://disney.go.com/disneyxd/' => 'disneyxd',
'http://www.engadget.com/rss.xml' => 'engadget',
'http://syndication.eonline.com/syndication/feeds/rssfeeds/video/index.xml' => 'eonline',
'http://sports.espn.go.com/espn/rss/news' => 'espn',
'http://facebook.com' => 'facebook',
'http://flickr.com/espn/rss/news' => 'flickr',
'http://www.fxnetworks.com//home/tonight_rss.php' => 'fxnetworks',
'http://www.hgtv.com/' => 'hgtv',
'http://www.history.com/this-day-in-history/rss' => 'history',
'http://rss.hulu.com/HuluRecentlyAddedVideos?format=xml' => 'hulu',
'http://rss.imdb.com/daily/born/' => 'imdb',
'http://www.metacafe.com/' => 'metacafe',
'http://feeds.feedburner.com/Monkeyseecom-NewestVideos?format=xml' => 'monkeysee',
'http://pheedo.msnbc.msn.com/id/18424824/device/rss/' => 'msnbc',
'http://www.nationalgeographic.com/' => 'nationalgeographic',
'http://dvd.netflix.com/NewReleasesRSS' => 'netflix',
'http://feeds.nytimes.com/nyt/rss/HomePage' => 'newyorktimes',
'http://www.nick.com/' => 'nickelodeon',
'http://www.nickjr.com/' => 'nickjr',
'http://www.pandora.com/' => 'pandora',
'http://www.pbskids.com/' => 'pbskids',
'http://www.photobucket.com/' => 'photobucket',
'http://feeds.reuters.com/Reuters/worldNews' => 'reuters',
'http://www.revision3.com/' => 'revision3',
'http://www.tbs.com/' => 'tbs',
'http://www.theverge.com/rss/index.xml' => 'theverge',
'http://www.tntdrama.com/' => 'tnt',
'http://www.tvland.com/' => 'tvland',
'http://www.vimeo.com/' => 'vimeo',
'http://www.vudu.com/' => 'vudu',
'http://feeds.wired.com/wired/index?format=xml' => 'wired',
'http://www.xfinitytv.com/' => 'xfinitytv',
'http://www.youtube.com/topic/4qRk91tndwg/most-popular#feed' => 'youtube',
);
$feed->set_feed_url(array_keys($urls));
$feed->enable_cache(true);
$feed->set_cache_location('cache');
$feed->set_cache_duration(1800); // Set the cache time
$feed->set_item_limit(0);
$success = $feed->init(); // Initialize SimplePie
$feed->handle_content_type(); // Take care of the character encoding
?>
<?php require_once("inc/connection.php"); ?>
<?php require_once("inc/functions.php"); ?>
<?php include("inc/header.php"); ?>
<?php
// Sort it
$feed_items = array();
$items = $feed->get_items();
$urls = array_unique($urls);
foreach ($urls as $url => $image) {
$unset = array();
$feed_items[$url] = array();
foreach ($items as $i => $item) {
if ($item->get_feed()->feed_url == $url) {
$feed_items[$url][] = $item;
$unset[] = $i;
}
}
foreach ($unset as $i) {
unset($items[$i]);
}
}
foreach ($feed_items as $feed_url => $items) {
if (empty($items)) {
?>
<div class="item"><img src="images/boreds/<?php echo $urls[$feed_url] ?>.png"/><p>Visit <?php echo $urls[$feed_url] ?> now!</p></div>
<?
continue;
}
$first_item = $items[0];
$feed = $first_item->get_feed();
?>
<?php
$feedCount = 0;
foreach ($items as $item ) {
$feedCount++;
?>
<div class="item"><strong id="amount"><?php echo $feedCount; ?></strong><img src="images/boreds/<?php echo $urls[$feed_url] ?>.png"/><p><?php echo $item->get_title(); ?></p></div>
<?php
}
}
?>
<?php require("inc/footer.php"); ?>
Maybe you can use this one:
$feed = new SimplePie();
$feed->set_feed_url('http://myfirstfeed','http://mysecondfeed');
foreach( $feed->get_items() as $k => $item ) {
echo "<div id='".$k.'">";
echo $item->get_permalink();
echo $title = $item->get_title();
echo $item->get_date('j M Y, g:i a');
echo $item->get_content();
echo "</div>";
}
Related
For some reach my array returns the data numerous times, for different arrays after filtering via a foreach in the second example the post only contains 1 unique link so the rest shouldn't exist at all, it should print simply the data from image_1 here's the PHP code.
$imagecounter = 1;
foreach ($html2->find('.post img') as $source) {
$link = $source->src;
if (strpos($link, 'https://www.example.com/wp-content/uploads/') !== false) {
$data['image_'.$imagecounter++.''] = $link;
}
}
And here's the array.
Array
(
[url] => https://www.example.com/something-with-data/
[featured_image] => https://www.example.com/wp-content/uploads/2018/11/something-1.jpg
[name] => Main Categories
[image_1] => https://www.example.com/wp-content/uploads/2018/11/something-11.jpg
[image_2] => https://www.example.com/wp-content/uploads/2018/10/something-1.jpg
[image_3] => https://www.example.com/wp-content/uploads/2018/10/something-1.png
[image_4] => https://www.example.com/wp-content/uploads/2018/10/something-2.jpg
[image_5] => https://www.example.com/wp-content/uploads/2018/11/something-3.jpg
[image_6] => https://www.example.com/wp-content/uploads/2018/11/something-4.jpg
[image_7] => https://www.example.com/wp-content/uploads/2018/11/something-5.jpg
[image_8] => https://www.example.com/wp-content/uploads/2018/11/something-6.jpg
[image_9] => https://www.example.com/wp-content/uploads/2018/11/something-7.jpg
[image_10] => https://www.example.com/wp-content/uploads/2018/11/something-8.jpg
[image_11] => https://www.example.com/wp-content/uploads/2018/11/something-9.jpg
)
Array
(
[url] => https://www.example.com/a-completely-different-post
[featured_image] => https://www.example.com/wp-content/uploads/2018/10/UmekRLrlwK8.jpg
[name] => Main Categories
[image_1] => https://www.example.com/wp-content/uploads/2018/10/UmekRLrlwK8.jpg (THIS IS FROM THE NEW ITERATION)
[image_2] => https://www.example.com/wp-content/uploads/2018/10/something-1.jpg
[image_3] => https://www.example.com/wp-content/uploads/2018/10/something-1.png
[image_4] => https://www.example.com/wp-content/uploads/2018/10/something-2.jpg
[image_5] => https://www.example.com/wp-content/uploads/2018/10/something-3.jpg
[image_6] => https://www.example.com/wp-content/uploads/2018/10/something-4.jpg
[image_7] => https://www.example.com/wp-content/uploads/2018/10/something-5.jpg
[image_8] => https://www.example.com/wp-content/uploads/2018/10/something-6.jpg
[image_9] => https://www.example.com/wp-content/uploads/2018/10/something-7.jpg
[image_10] => https://www.example.com/wp-content/uploads/2018/10/something-8.jpg
[image_11] => https://www.example.com/wp-content/uploads/2018/10/something-9.jpg
[image_12] => https://www.example.com/wp-content/uploads/2018/10/something-10.jpg
)
Start with an empty $data array.
$data = [];
$imagecounter = 1;
foreach ($html2->find('.post img') as $source) {
$link = $source->src;
if (strpos($link, 'https://www.example.com/wp-content/uploads/') !== false) {
$data['image_'.$imagecounter++.''] = $link;
}
}
If you need to store multiple sets of $data, then you can store each new $data batch in a parent array.
foreach ($htmls as $html2) {
$data = [];
$imagecounter = 1;
foreach ($html2->find('.post img') as $source) {
$link = $source->src;
if (strpos($link, 'https://www.example.com/wp-content/uploads/') !== false) {
$data['image_'.$imagecounter++.''] = $link;
}
}
$result[] = $data;
}
Here is the example code:
<?php
$arr = array(
array(
'company' => array(
'code' => 'ccd1',
'name' => 'cnm1'
) ,
'products' => array(
array(
'code' => 'pcd1',
'name' => 'pnm1'
) ,
array(
'code' => 'pcd2',
'name' => 'pnm2'
)
)
) ,
array(
'company' => array(
'code' => 'ccd2',
'name' => 'cnm2'
) ,
'products' => array(
array(
'code' => 'pcd1',
'name' => 'pnm1'
) ,
array(
'code' => 'pcd2',
'name' => 'pnm2'
) ,
array(
'code' => 'pcd3',
'name' => 'pnm3'
)
)
)
);
echo "<pre>"; print_r($arr); echo "</pre>";
$AI = 1;
foreach($arr as $value){
$total_products = count($value['products']);
echo $AI++.".{$value['company']['name']} ({$total_products})<br />";
foreach($value['products'] as $value2){
echo " ".$value2['name']."<br />";
}
}
I don't know how to explain it, but what I want is to add auto increment in sub foreach loop, like this:
1.cnm1 (2)
1.pnm1
2.pnm2
2.cnm2 (3)
1.pnm1
2.pnm2
3.pnm3
Usually you can just use the foreach keys plus one. As another alternative, if this is just for presentation, just use ordered lists:
echo '<ol>';
foreach($arr as $ar1) {
echo '<li>' . $ar1['company']['name'] . ' (' . count($ar1['products']) . ')</li>';
echo '<ol>';
foreach($ar1['products'] as $ar2) {
echo "<li>{$ar2['name']}</li>";
}
echo '</ol>';
}
It'll number those items accordingly. No need for addition. Plus you can use CSS to style the list,
You can access the key/index of an foreach :
foreach($arr as $i => $value){
$total_products = count($value['products']);
echo ($i+1).'.'.$value['company']['name'].' ('.$total_products .')<br />';
foreach($value['products'] as $j => $value2){
echo ' '.($j+1).'.'.$value2['name'].'<br />';
}
}
Here you go.
$arr = array(array('company'=>array('code'=>'ccd1', 'name'=>'cnm1'), 'products'=>array(array('code'=>'pcd1', 'name'=>'pnm1'), array('code'=>'pcd2', 'name'=>'pnm2'))), array('company'=>array('code'=>'ccd2', 'name'=>'cnm2'), 'products'=>array(array('code'=>'pcd1', 'name'=>'pnm1'), array('code'=>'pcd2', 'name'=>'pnm2'), array('code'=>'pcd3', 'name'=>'pnm3'))));
echo "<pre>";
print_r($arr);
echo "</pre>";
$AI = 1;
foreach($arr as $value)
{
$total_products = count($value['products']);
echo $AI++.".{$value['company']['name']} ({$total_products})<br />";
$k = 0;
foreach($value['products'] as $value2)
{
echo " ".$k++.". ".$value2['name']."<br />";
}
}
This also worked for me:
foreach($value['products'] as $key2=>$value2){
$AI2 = $key2+1;
echo " ".$AI2.".{$value2['name']}<br />";
}
You can try this:
foreach($arr as $value){
$total_products = count($value['products']);
echo $AI++.".{$value['company']['name']} ({$total_products})<br />";
$sub=1;
foreach($value['products'] as $value2){
echo " ".$sub++.'.'.$value2['name']."<br />";
}
}
I have an array in $xml->channel->item which outputs correctly if I run:
foreach ($xml->channel->item as $entry){
echo $entry->title;
echo $entry->category;
echo $entry->pubDate;
}
Now, I am struggling to make this array work with the following form, which outputs a formatted table:
$rows = array(
'row[0]' => array('title' => 'Test Title','category' => 'Computer', 'date' => 'test date'),
'row[1]' => array('title' => 'Test Title 2','category' => 'Chemical', 'date' => 'test date'),
);
$form['table'] = array(
'#type' => 'tableselect',
'#header' => $header,
'#options' => $rows,
);
I tried this code, but it didn't work:
$i=0;
foreach ($xml->channel->item as $rows){
row[$i][title] = $rows->title;
row[$i][category] = $rows->category;
row[$i][date] = $rows->pubDate;
$i=++;
}
SOLUTION:
Copying the solution I figured out from the comment below to the post body:
$rows = array();
foreach ($xml->channel->item as $entry) {
$row['title'] = $entry->title;
$row['category'] = $entry->category;
$row['date'] = $entry->pubDate;
array_push($rows, $row);
}
Finally figured out. I hope this will save others hitting the similar task:
$rows = array();
foreach ($xml->channel->item as $entry) {
$row['title'] = $entry->title;
$row['category'] = $entry->category;
$row['date'] = $entry->pubDate;
array_push($rows, $row);
}
So right now i have an array named $socialMeta, containing:
Array (
[0] => Array (
[socialFacebook] => Array (
[0] => http://www.facebook.com/someUsername
)
)
[1] => Array (
[socialYoutube] => Array (
[0] => http://www.youtube.com/user/someUsername
)
)
[2] => Array (
[socialSoundcloud] => Array (
[0] => http://www.soundcloud.com/someUsername
)
)
)
From this array I need to create the following output:
<div class="social">
Add us on <span>Facebook</span>
Visit us on <span>Youtube</span>
Visit us on <span>Souncloud</span>
</div>
Please not that there are different anchor text for the first link.
For anchor classes i can use $socialMeta key to make whole process a bit easier.
<?php if (!empty($socialMeta)) { ?>
<div class="social">
<?php foreach ($socialMeta as $rows) {?>
<?php foreach ($rows as $key => $val) {?>
<?php
switch ($key) {
case "socialFacebook":
$title = "Facebook";
$class = "fb";
break;
case "socialYoutube":
$title = "Youtube";
$class = "yt";
break;
case "socialSoundcloud":
$title = "Souncloud";
$class = "sc";
break;
}
?>
Add us on <span><?php echo $title; ?></span>
<?php }?>
<?php }?>
</div>
<?php }?>
Start by identifying the network for each element in the array (I assume the name is $array in the following examples):
function add_network($array) {
static $networks = array('Facebook', 'Youtube', 'Soundcloud');
foreach($networks as $network)
if (isset($array['social' . $network])) {
$array['network'] = $network;
return $array;
}
//None found
$array['network'] = false;
return $array;
}
$array = array_map('add_network', $array);
Then transform the array (you should find a better name for this function):
function transform_array($a) {
static $classes = array('Youtube' => 'yt', 'Facebook' => 'fb', 'Soundcloud' => 'sc');
$network = $a['network'];
$class = $classes[$network];
$url = $a['social' . $network][0]
return array('network' => $network,
'url' => $url,
'class' => $class);
}
$array = array_map('transform_array', $array);
And now just loop over the elements of $array:
foreach($array as $row) {
$network = $row['network'];
$url = $row['url'];
$class = $row['class'];
if ($network === 'Facebook')
$link_text = 'Add us on <span>%s</span>';
else
$link_text = 'Visit us on <span>%s</span>'
$link_text = sprintf($link_text, $network);
printf('%s',
$url, $class, $link_text);
}
<?php
function flattenArray(array $input){
$nu = array();
foreach($input as $k => $v){
if(is_array($v) && count($v) == 1){
$nu[key($v)] = current($v);
if(is_array($nu[key($v)]) && count($v) == 1)
$nu[key($v)] = current($nu[key($v)]);
}
else
$nu[$k] = $v;
}
return $nu;
}
// here you can maintain the sortorder of the output and add more social networks with the corresponding URL-text...
$urlData = array(
'socialFacebook' => 'Add us on <span>Facebook></span>',
'socialYoutube' => 'Visit us on <span>Youtube</span>',
'socialSoundcloud' => 'Visit us on <span>Souncloud</span>',
);
$testArray = array(
array('socialFacebook' => array('http.asdfsadf')),
array('socialYoutube' => array('http.asdfsadf')),
array('socialSoundcloud' => array('http.asdfsadf'))
);
$output = flattenArray($testArray);
HERE WE GO
echo '<div class="social">';
foreach($urlData as $network => $linkText){
if(!empty($output[$network]))
echo sprintf('%s</span>', $output[$network], $linkText);
}
echo '</div>';
I want to merge array which have same key to be one. Example
$options = array(
array("group" => "header","title" => "Content 1"),
array("group" => "header","title" => "Content 2"),
array("group" => "menu","title" => "Content 3"),
array("group" => "content","title" => "Content 4"),
array("group" => "content","title" => "Content 5"),
array("group" => "content","title" => "Content 6"),
array("group" => "footer","title" => "Content 7")
);
foreach ($options as $value) {
if ($value['group']) {
echo "<div class='{$value['group']}'>";
echo $value['title'];
echo "</div>";
}
}
Current output is
<div class='header'>Content 1</div><div class='header'>Content 2</div><div class='menu'>Content 3</div><div class='content'>Content 4</div><div class='content'>Content 5</div><div class='content'>Content 6</div><div class='footer'>Content 7</div>
What I want here is to be
<div class='header'>
Content 1
Content 2
</div>
<div class='menu'>
Content 3
</div>
<div class='content'>
Content 4
Content 5
Content 6
</div>
<div class='footer'>
Content 7
</div>
Let me know
$grouped = array();
foreach($options as $option) {
list($group, $title) = array_values($option);
if (!isset($grouped[$group])) {
$grouped[$group] = array();
}
$grouped[$group][] = $title;
}
foreach ($grouped as $group => $titles) {
echo sprintf('<div class="%s">%s</div>', $group, implode('', $titles));
}
$groups = array ();
foreach ( $options as $value ) {
if ( !isset ( $groups[$value['group']] ) ) {
$groups[]['group'] = $value['group']
}
$groups[$value['group']]['title'][] = $value['title'];
}
foreach ( $groups as $group ) {
echo "<div class="{$group['group']}">";
echo implode ( "\n", $group['title'] );
echo "</div>";
}
This should work, but if it doesn't matter to you, you could also just change the structure of your hardcoded-array, then you wouldn't need my first foreach.