How to echo an array of associative arrays? - php

I have this code:
foreach($html->find('ul.results') as $article) {
$item['date'] = $article->find('span.result_date', 0)->plaintext;
$item['title'] = $article->find('a.result_title', 0);
$item['text'] = $article->find('span.result_text', 0)->plaintext;
$item['read'] = $article->find('a.read_more', 0);
$articles[] = $item;
}
foreach ($articles as &$item) {
while ($i < 5) {
echo $item['date']." ";
echo $item['title'].'</br>';
echo $item['text']." ";
echo $item['read'].'</br></br>';
$i++;
}
}
And I am trying to echo the results. Right now the second foreach isn't doing anything. It is just displaying five of the same articles. The articles are in the format of: date, title, text, read more. I am trying to eco the first five $articles, but I can't find a proper way to do so that isn't print_r.

The whole loop inside the for each will just loop on the first element 5 times, move to the next element and loops 5 times, etc.
Try something like this:
$i = 0;
foreach ($articles as $item){
echo items stuff...
$i++;
if ($i == 5) break;
}

Related

How to loop through two xml files?

I have two xml files that look like this:
First:
<numbers>
<line><value>a1</value></line>
<line><value>a2</value></line>
<line><value>a3</value></line>
</numbers>
Second:
<numbers>
<line><value>b1</value></line>
<line><value>b2</value></line>
<line><value>b3</value></line>
</numbers>
Right now I have double foreach loops (I know it should be something else, for loop maybe?)
$xmldata = simplexml_load_file('file.xml');
$xmldata2 = simplexml_load_file('file2.xml');
foreach($xmldata->line as $item){
foreach($xmldata2->line as $item2){
echo $item->value;
echo $item2->value. "</p>";
}
}
But the output is this:
a1b1
a1b2
a1b3
a2b1
a2b2
a2b3
a3b1
a3b2
a3b3
Should be:
a1b1
a2b2
a3b3
Not sure of the logic but this would achieve what you say you want to achieve.
$xmldata = simplexml_load_file('file.xml');
$xmldata2 = simplexml_load_file('file2.xml');
$key = 0;
foreach($xmldata->line as $item){
echo '<p>';
echo $item->value;
echo $xmldata2->line[$key]->value;
echo "</p>";
$key++;
}
RESULT
<p>a1b1</p>
<p>a2b2</p>
<p>a3b3</p>
But if it is possible that the 2 xml files may not be the same length this might be safer.
$xmldata = simplexml_load_file('file.xml');
$xmldata2 = simplexml_load_file('file2.xml');
// only loop for the number of occurances in the smallest xml file
$max = count($xmldata) >= count($xmldata2) ? count($xmldata2) : count($xmldata);
for ($key=0; $key < $max; $key++){
echo '<p>';
echo $xmldata->line[$key]->value;
echo $xmldata2->line[$key]->value;
echo "</p>";
}

returing nodeValues using while loop

I am using xpath to get various elements on a page. If I use a foreach loop like this foreach ($company as $node) { echo $node->nodeValue. "<br>"; } it works but I am only able to return values from one variable so that means I have to create two separate foreach loops. I want to be able to use the while loop so I can return both values from variable at the same time. The while loop doesnt return any error or values.
$doc = new DOMDocument();
#$doc->loadHTML($source);
$xpath = new DOMXpath($doc);
$company = $xpath->query("//*[#class='name']");
$address = $xpath->query("//*[#class='address']");
$i = 0;
while ($i < count($company)) {
echo $company->nodeValue. "<br>";
echo $address->nodeValue. "<br><br>";
$i++;
}
They are NodeLists, to retrieve individual nodes by index, use ->item()
while ($i < $company->length ) {
echo $company->item($i)->nodeValue. "<br>";
echo $address->item($i)->nodeValue. "<br><br>";
$i++;
}

How do I break a foreach loop after it has looped for a set desired number of times instead of the entire array in PHP? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
limiting number of times a loop runs in php
I am trying to break a foreach loop reading a feed of tweets - after three tweets. Would somebody help with the code I need to supplement to the one i have already.
<?php
function getTweets($Username) {
$feedURL = "http://twitter.com/statuses/user_timeline.rss?screen_name=" . $username;
$content = file_get_content($feedURL);
$tweets = new SimpleXMLElement ($content);
foreach ($tweets->channel->item as $tweet) {
echo "<ul>";
echo "<li>$tweet->description<br />$tweet->pubDate</li>";
echo "</ul>";
}
?>
}
Thanking you in advance.
Probably like this.
$max_count = 3;
$counter = 0;
foreach ($tweets->channel->item as $tweet) {
echo "<ul>";
echo "<li>$tweet->description<br />$tweet->pubDate</li>";
echo "</ul>";
if($counter == $max_count){
break;
}
$counter++;
}
You can use break
foreach ($tweets->channel->item as $tweet) {
echo "<ul>";
echo "<li>$tweet->description<br />$tweet->pubDate</li>";
echo "</ul>";
if( someCondition )
{
break;
}
}
I assume items are indexed:
foreach ($tweets->channel->item as $i => $tweet) {
echo "<ul>";
echo "<li>$tweet->description<br />$tweet->pubDate</li>";
echo "</ul>";
if ($i == 2) {
break;
}
}

Limit results in PHP using while loop

I have a list of returned subcategories. I only have access to the template display and not to the MySQL query so no, I can't limit the query.
Right now all the results are returned. I would like to limit the list to 5, and then add a "more" link if there are more than 5 results.
I know I did this wrong because I don't think count is actually tied to the foreach:
<ul class="sub-categories">
<?php
while (count($category->getChildren()) <= 5) { // line I added for while loop
foreach ($category->getChildren() as $child) {
if (!$child->totalItemCount())
continue;
$link = $this->app->route->category($child);
$item_count = ($this->params->get('template.show_sub_categories_item_count')) ? ' <span>('.$child->totalItemCount().')</span>' : '';
echo '<li>'.$child->name.''.$item_count.'</li>';
}
} // line I added for while loop
?>
</ul>
Keep track within the foreach and break; when you've reached the limit:
<ul class="sub-categories">
<?php
$i = 0;
foreach ($category->getChildren() as $child) {
if (!$child->totalItemCount()) continue;
$i++; if($i>5) break;
$link = $this->app->route->category($child);
$item_count = ($this->params->get('template.show_sub_categories_item_count')) ? ' <span>('.$child->totalItemCount().')</span>' : '';
echo '<li>'.$child->name.''.$item_count.'</li>';
}
?>
</ul>

PHP + RSS duplicate elements

Im using this PHP to get a list of Title's from an RSS feed:
<?php require_once('magpie/rss_fetch.inc');
$rss = fetch_rss('http://live.visitmix.com/Sessions/RSS');
foreach ($rss->items as $item) {
$cat = $item['category'];
$title = $item['title'];
echo '<li class="'.$cat.'">'.$title.'</li>';
}
?>
I want to use <category> and add it as the class, however the <category> element appears for each <item> 1,2,3,4 or more times depending on the Title. How can I take the category element and seperate each category with a space if there is more than 1?
what about accumulating the categories in an array and then implode the array?
$categoriesArray = array();
foreach ($rss->items as $item) {
array_push($categoriesArray, $item['category']);
}
$categories = implode(" ", $categoriesArray);
EDIT TO ADD
If the categories are cumulated, you can try something like this:
$categoriesByTitle = array();
foreach ($rss->items as $item) {
$currentTitle = $item['title'];
$categories = $categoriesByTitle[$currentTitle];
if ($categories == NULL) {
$categories = array();
$categoriesByTitle[$currentTitle] = $categories;
}
if (!in_array($item['category'], $categories)) {
array_push($categories, $item['category']);
}
}
foreach ($categoriesByTitle as $title=>$category) {
// use implode for each title
$categoryString = implode(" ", $category);
echo '<li class="'.$categoryString.'">'.$title.'</li>';
}
Check this reference for arrays, it could be very useful for dealing with this kind of problems

Categories