Outputting the count in a foreach function - php

I am working with SimplePie and I cannot figure out how to output the count, or the key values for the loop.
Shouldn't this
<?php foreach ($feed->get_items() as $item): ?>
<?php
$i = key($item);
echo $i;
?>
<?php endforeach; ?>
, or this
<?php foreach ($feed->get_items() as $item): ?>
<?php
$i = count($item);
echo $i;
?>
<?php endforeach; ?>
be outputting a unique number for each?
uniqid() Doesn't work in this case, because I am running the loop twice on the page and trying to match up one list of elements with another based on ID.

A single argument used with as is interpreted as a variable in which to store the value, not the key. If you want the key, you need to use => in a manner like the following:
foreach ($feed->get_items() as $key => $item):
echo $key;
endforeach
As a sidenote, you're using key() and count() on an item in the array, rather than the array as a whole, which is invalid. As far as I'm aware, there's no guarantee that key() will work as you expect even if applied to the whole array. It's meant for loops where you control the iteration, as with next.

To get the 'count' in a foreach you would need an extra variable. Getting the key is easy and the same if the array is indexed in order instead of associative. Here is an example including both:
$array = array(
'foo' => 'bar'
);
$i = 0;
foreach ($array as $key => $value)
{
/*
code where $i is the 'count' (index) and $key is the associative $key.
*/
/* $i == 0 */
/* $key == 'foo' */
/* $value == 'bar' */
$i++;
}
key($item) that you're using above doesn't work because you're trying to get the key of a value that no longer is associated with the original array.
count($item) is the count of a subarray $item.

you can use get_id() method
like :
foreach ($feed->get_items() as $item)
{
$prev_ids = array('guid1', 'guid2', 'guid3', 'guid4');
if (in_array($item->get_id(true), $prev_ids))
{
echo "This item is already stored.";
}
else
{
echo "This is a new item!";
}
}

Related

How to declare, insert and iterate a php associative array with an associative array as value?

I need to work with a hashtable which values can store variables like:
$numberOfItems
$ItemsNames
If I ain't wrong, that would mean another hash like array as value.
What should be the right syntax for inserting and iterating over it?
Is anything like:
$hash['anyKey']=>$numberOfItems=15;
$hash['anyKey']=>$ItemsNames=['f','fw'];
valid?
if there's no chance to have collusion in item name, you can use the name in key
$hash[$ItemsName] = $numberOfItems;
in the other case, use an integer for example as a key, then the different "attributes" you want as keys for the 2nd array
$hash[$integer]["count"] = $numberOfItems;
$hash[$integer]["name"] = $name;$
Then, for iterating (1st case):
foreach ($hash as $name => $number) {
echo $number;
echo $name;
}
or, 2nd case
foreach ($hash as $item) {
echo $item["name"];
echo $item["count"];
}
To create php array, which can be a hash table, you can do:
$arr['element'] = $item;
$arr['element'][] = $item;
$arr['element'][]['element'] = $item;
Other way:
$arr = array('element' => array('element' => array(1)));
To iterate over it use foreach loop:
foreach ($items as $item) {
}
It's also possible to create nested loops.
About your case:
$hash['anyKey']=>$numberOfItems=15;
$hash['anyKey']=>$ItemsNames=['f','fw'];
I would do:
$hash['anyKey']['numberOfItems'] = 15;
$hash['anyKey']['ItemsNames'] = array('f','fw');

Nested looping with an associative array of arrays, getting no output (PHP)

Thanks in advance for looking.
I am trying to build some HTML using a foreach loop with a few layers of arrays.
Groups of data and groups of titles for that data are stored in sets of arrays.
In turn, those arrays of data are stored in an array ($titlegroups and datagroups).
The aim being to set up a nested loop, where each group of data and titles populate the relevant fields in some html.
Here is a full set of code (structure) of my attempt.
$a=1;
$b=2;
$c=3;
$d=4;
$titlesA=array('string1','string2');
$titlesB=array('string3','string4');
$dataA=array($a,$b);
$dataB=array($c,$d);
$titlegroups=array($titlesA,$titlesB);
$datagroups=array($dataA,$dataB);
$groups=array(array_combine($titlegroups, $datagroups));
$j=0;
foreach($groups as $titlesX => $dataX)
{
$j++;
echo'<div class="something">';
$i=0;
foreach(array_combine($titlesX, $dataX) as $title => $var)
{
$i++;
echo '
<li>'.$title.'</li><input name="'.$j.'x'.$i.'" value="'.$var.'" />
';
}
echo '</div>';
}
Checking it in ideone I get the error:
Warning: array_combine() expects parameter 1 to be array, integer
given in /home/0zw0mb/prog.php on line 26
Line 26 is:
foreach(array_combine($titlesX, $dataX) as $title => $var)
but $titlesX and $dataX should both be arrays?
If anyone can set me straight I'd appreciate it. Thanks.
You can't have arrays as keys, they are converted to strings. You logic required some changes and an additional sentinel variable ($idx), to tell when the code crosses one group to another.
array_merge was necessary due to the key requirements of arrays.
Check the below code:
$a=1;
$b=2;
$c=3;
$d=4;
$titlesA=array('string1','string2');
$titlesB=array('string3','string4');
$dataA=array($a,$b);
$dataB=array($c,$d);
$titlegroups=array_merge($titlesA,$titlesB);
$datagroups=array_merge($dataA,$dataB);
$items=array_combine($titlegroups, $datagroups);
$indexes = array(count($dataA), count($dataB));
$i = 0;
$j = 0;
$idx = $indexes[$j];
echo '<div class="something">';
foreach($items as $title => $var)
{
echo '
<li>'.$title.'</li><input name="'.$j.'x'.($i++).'" value="'.$var.'" />
';
$idx--;
if ($idx == 0) {
/* End of a group */
echo '</div>';
$idx = $indexes[++$j];
/* If there is another group, create new container */
if ($idx != null) {
echo '<div class="something">';
}
}
}

Count results inside foreach then store that value in a variable to be used elsewhere

How do you count the results inside a foreach then store that value in a variable to be used on another foreach.
Example. This foreach returns 5 items
foreach ($xml->items as $item) {
echo "$item->name";
echo "$item->address";
}
Now I want that the foreach above be counted and stored in say $totalitems and be used on another foreach. This second foreach also counts its results and store in $totalitems2. Something like this:
foreach ($xml->items as $item) { //Same source but they will be displayed separately based on a condition.
echo "$item->name";
echo "$item->address";
if_blah_blah_meet_condition_then_break;
}
So basically what I want here is to restrict the total number of items being displayed on both foreach combined. $totalitems and $totalitems2 should have the sum of 8. 8 is the number I want limit the items returned. Doesn't matter if the other foreach has more items than the other. 3 and 5. 4 and 4. 6 and 2. Etc.
How can I achieve this? Please advice.
Just use the simple iterator ++ methods. When you are on the second foreach, watch for when $i passes the number that you want to stop it.
Code:
$i = 0;
foreach ($xml->items as $item) {
echo "$item->name";
echo "$item->address";
$i++;
}
foreach ($xml->items as $item) {
echo "$item->name";
echo "$item->address";
$i++;
if ($i > 5) { // or whatever the number is
break;
}
}
$totalItems = count($xml->items);
foreach ($xml->items as $item) {
echo "$item->name";
echo "$item->address";
}
Just use count($xml->items) and that value in the condition, inside the loop.
It seems your array is stored in xml->items therefor, you only would have to save it in another variable if you want to store it.
foreach ($xml->items as $cont=>$item) {
echo "$item->name";
echo "$item->address";
if($cont<8){
$totalItems_one[] = $item;
}
}
//whatever changes you do to $xml->items
foreach ($xml->items as $cont=>$item) {
echo "$item->name";
echo "$item->address";
if($cont<8){
$totalItems_two[] = $item;
}
}
Like this you have the two new arrays totalItems_one and totalItems_two and you can get the number of items just doing count($totalItems_one) or count($totalItems_two) whenever you want.

object foreach loop iterate only even values

Basically I have a set of object values I want render in 2 separate html lists
I figure the simplest way to do this is by displaying evens only in one list, and odd only in the other
Here is the current code for displaying a single list
<ul>
<?php foreach ($values as $value) : ?>
<li><?php echo $value->value; ?></li>
<?php endforeach; ?>
</ul>
Try this:
<ul>
<?php
/* read the index key */
foreach ($values as $key => $value) :
/* skip the current element if it doesn't have an even index */
if($key % 2 == 1) continue;
?>
<li><?php echo $value->value; ?></li>
<?php endforeach; ?>
You didn't specify if the array has integer index. So I use a separate index pivot. This will do.
$v=array();
$index = 1;
foreach ($values as $value){
$v[($index++)%2][]=$value->value;
}
list ($evens, $odds) = $v;
echo "<ul><li>".implode("</li><li>", $odds)."</li></ul>"; // show list of odds
echo "<ul><li>".implode("</li><li>", $evens)."</li></ul>"; // shows list of even

How to get last key with values from array of arrays? PHP

This is what i am currently using
<?php $sidebar = $this->data['sidebar'];
$lastKey = array_pop(array_keys($sidebar));
$sidebar = $this->data['sidebar'][$lastKey]; ?>
<?php foreach($sidebar as $key => $item) { ?>
<li id="<?php echo Sanitizer::escapeId( "pt-$key" ) ?>"<?php
if ($item['active']) { ?> class="active"<?php } ?>><?php echo htmlspecialchars($item['text']) ?></li>
<?php } ?>
This is what i get (http://pastebin.com/t6Y2ZtMF) when i print_r($sidebar);
I want to get the last Array which is Categories and turn it into links.
I am new to php, so my method could be wrong even though it works. I is there a right way to pull the Categories Array or the above code is good as it is?
$lastValue = end($array);
$lastKey = key($array); // current key, which is the last since you called end()
After update:
You don't seem to be needing the key, only the array:
<?php $lastSidebarValue = end($this->data['sidebar']); ?>
<?php foreach ($lastSidebarValue as $key => $item) : ?>
business as usual...
<?php endforeach; ?>
Since you know you want the key 'Categories' though (not the last key), this seems the most logical thing to do:
<?php foreach ($this->data['sidebar']['Categories'] as $key => $item) : ?>
business as usual...
<?php endforeach; ?>
I think the end() function would be a great solution: http://php.net/manual/en/function.end.php
It basically returns the value of the last element in the array being passed to it.
$sidebar = end($sidebar);
If you want to get a key/value pair without popping & pushing the array, set the internal cursor to the end of the array and then use list and each to get the key & value.
// set up your array however you had it
$array = ...;
// move the cursor to the end of the array
end($array);
// use list() and each() to extract your key/value pair
list($key,$val) = each($array);
// $key will now have the last key
// $val will have the last value
perhaps, end:
$fruits = array('apple', 'banana', 'cranberry');
echo end($fruits); // cranberry
You can use `end()` instead of `array_pop()`. But both works for the **last element** of the array. The only difference is `end()` **points out** the **last element** of the array without effecting it and `array_pop()` **pops** the element off the **end** of array.
Please go through the following links for detail information
end() | array_pop()

Categories