generate unique ID for on foreach loop? - php

Current I use toggle to show/hide details. I need to give each div a unique ID in foreach loop. I'm not sure how to make it works on an echo string. Can you help me?
<?php
$i = 0;
foreach ( $payment as $payment_id => $items ) {
foreach ( $items as $item ) {
$i++;
$count = 0;
// Echo, need to show unique ID in both $count, it must be the same
echo '<p><strong>Link</strong>
<br/>Show Details
<div id="payment_info_'.$count.'" style="display:none;">';
++count;
}
}
?>
I need to make $count in 2 position on the code is same. I got error with this code.
Thank you
Updated:
Actually the code is not just as I give here. I tried with your code but doesnt work.
You can view full at http://www.codesend.com/view/7d58acb2b1c51149440984ec6568183d/ (pasw:123123)

You've writen ++count instead of ++$count
It seems you're not using $i.
You're initializing $count on every loop.
This is supposed to work:
<?php
$i = 0; /* Seems redundant */
$count = 0;
foreach ( $payment as $payment_id => $items ) {
foreach ( $items as $item ) {
$i++; /* Seems redundant */
// Echo, need to show unique ID in both $count, it must be the same
echo '<p><strong>Link</strong>
<br/><a href="#" class="show_info"
id="dtls'.$count.'">Show Details</a>
<div id="payment_info_'.$count.'" style="display:none;">';
++$count;
}
}
?>

++count is wrong, it should be ++$count;
try this
<?php
$i = 0;
foreach ( $payment as $payment_id => $items ) {
foreach ( $items as $item ) {
$i++;
$count = 0;
// Echo, need to show unique ID in both $count, it must be the same
echo '<p><strong>Link</strong>
<br/>Show Details
<div id="payment_info_'.$count.'" style="display:none;">';
++$count;
}
}
?>

first:
remove this or put it outside of the foreach loop :
$count = 0;
second:
don't use only number for id and use it with a character or word like this :
id = "element'.$count.'"
Third :
what is $i ?
if it's useless remove it!
Forth
change ++count to ++$count
CODE :
<?php
$i = 0;
$count = 0;
foreach ( $payment as $payment_id => $items ) {
foreach ( $items as $item ) {
$i++;
// Echo, need to show unique ID in both $count, it must be the same
echo '<p><strong>Link</strong>
<br/>Show Details
<div id="payment_info_'.$count.'" style="display:none;">';
++$count;
}
}
?>

Related

Count groups in loop foreach

My Script :
<?php
$values='Product1,54,3,888888l,Product2,54,3,888888l,';
$exp_string=explode(",",$values);
$f=0;
foreach($exp_string as $exp_strings)
{
echo "".$f." - ".$exp_string[$f]." ";
if ($f%3==0)
{
print "<br><hr><br>";
}
$f++;
}
?>
With this code i want show data inside loop, the idea it´s show all information in groups the elements in each group it´s 4 elements and must show as this :
Results :
Group 1 :
Product1,54€,3,green
Group 2:
Product2,56€,12,red
The problem it´s i don´t know why, don´t show as i want, and for example show separate some elements and not in group, thank´s , regards
It looks like you are trying to combine elements of a for loop and a foreach loop.
Here is an example of each, pulled from the php manual:
For Loop
for($index = 0, $index < size($array), $index++ {
//Run Code
//retrieve elements from $array with $array[$index]
}
Foreach
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
It's hard for me to understand what your input looks like. If you post an example of $exp_strings, I could be of better assistance. But from the sound of your question, if $exp_strings is multidimensional if you need to loop through groups of items, you could try nesting one loop inside another loop like so:
$groups_of_data = array(array(...), array(...), array(...));
for($i = 0, $i < size($groups_of_data), $i++) {
$group = $i;
for($j = 0, $j < size($groups_of_data[$i]), $j++) {
// print out data related to group $i
}
}
This is really all guesswork on my part though as I can't see what your input string/array is. Can you post that? Maybe I can be of more help.
here is code i worked out. it was kind of since i did't know what object $exp_string is. if it's a string you should tokenize it, but i think it's array from database. there was another problem, with your code where it tries to output $exp_string[$f] it should be $exp_strings what changes in the loop.
my code
$exp_string=array("Product"=>54,"price"=>3,"color"=>"green");
$f=0;
foreach($exp_string as $key => $exp_strings)
{
if($f%3==0)
{
print "<br><hr><br>";
echo "Product ".$exp_strings."<br> ";
}
else if($f%3==1)
{
echo "Price ".$exp_strings."<br> ";
}
else if($f%3==2)
{
echo "Color ".$exp_strings."<br> ";
}
$f++;
}
hope it's any help, maybe not what you wanted.
$values='Product1,1,2,3,Product2,1,2,3,Product3,1,2,3';
$products = (function($values) {
$exp_string = explode(',', $values);
$products = [];
for ($i=0; $i+3<count($exp_string); $i+=4) {
$product = [
'title' => $exp_string[$i],
'price' => $exp_string[$i+1],
'color' => $exp_string[$i+2],
'num' => $exp_string[$i+3],
];
array_push($products, $product);
}
return $products;
})($values);
/* var_dump($products); */
foreach($products as $product) {
echo "{$product['title']},{$product['price']},{$product['color']},{$product['num']}<br>";
}

Array get 2nd item

foreach($xml->xpath( 'programme[#channel="1"]' ) as $item) {
if (something) {
echo "cat.: ".$item->{'category'}. "<br>";}
If i have 2x "category" to choose, how to set it to get the second one, not the 1st in the row?
The simplest way would be to use a counter variable:
$i = 0;
foreach($xml->xpath( 'programme[#channel="1"]' ) as $item) {
if ( $i++ != 1)
echo "cat.: ".$item->{'category'}. "<br>";
However, this will include every category after the first. If you only want the second category, you could use the same approach:
$i = 0;
foreach($xml->xpath( 'programme[#channel="1"]' ) as $item) {
if ( $i++ == 2)
echo "cat.: ".$item->{'category'}. "<br>";
This gives you the second category and also ensures that you'll get the first category when there's no second one:
foreach ($xml->xpath('programme[#channel="1"]') as $item) {
if (something) {
if (isset($item->category[1]) && !empty($item->category[1])) {
echo 'cat.: '.$item->category[1].'<br />';
} else {
echo 'cat.: '.$item->category[0].'<br />';
}
}
}

How to define a PHP object as the last item in an array?

In the code below I want to apply the object "$activeclass" as a DIV class. I thought the end pointer I included would apply this only to the last iteration of the array, but instead it is applying the class to all iterations.
<div id="right_bottom">
<?
$content = is_array($pagedata->content) ? $pagedata->content : array($pagedata->content);
foreach($content as $item){
$activeclass = end($content) ? 'active' : ' ';
?>
<div id="right_side">
<div id="<?=$item->id?>" class="side_items <?=$activeclass?>">
<a class="content" href="<?=$item->id?>"><img src="<?=PROTOCOL?>//<?=DOMAIN?>/img/content/<?=$item->image?>"><br />
<strong><?=$item->title?></strong></a><br />
<h2><?=date('F j, Y', strtotime($item->published))?></h2><br />
</div>
</div>
<?
}
?>
</div>
Any ideas where I am making a mistake? How can I apply the class $activeclass only to the last iteration of my "foreach" statement?
The simplest way is to keep a count:
$i = 0; $size = count( $content);
foreach( $content as $item) {
$i++;
$activeclass = ( $i < $size) ? '' : 'active';
}
Alternatively, you can compare the last element with the current element (if your array is consecutively numerically indexed starting with 0 [Thanks to webbiedave for pointing out the assumptions made by this method]):
$last = count( $content) - 1;
foreach( $content as $item) {
$activeclass = ( $content[$last] === $item) ? 'active' : '';
}
Note that this approach will not work if your array has duplicate items.
Finally, you can compare indexes in the following way:
// Numerical or associative
$keys = array_keys($content);
$key = array_pop($keys); // Assigned to variables thanks to webbiedave
// Consecutive numerically indexed
$key = count( $content) - 1;
foreach( $content as $current_key => $item) {
$activeclass = ( $current_key === $key) ? 'active' : '';
}
$activeclass = end($content) ? 'active' : ' ';
The end() function returns the last element in the array, so you're basically checking to see if the array has a last element (which it always will, unless it's empty).
This is an explanation of what you're doing wrong - nick has the answer for how to fix it by using a counter.
Try this approach from the following link http://blog.actsmedia.com/2009/09/php-foreach-last-item-last-loop/
$last_item = end($array);
$last_item = each($array);
reset($array);
foreach($array as $key => $value)
{
// code executed during standard iteration
if($value == $last_item['value'] && $key == $last_item['key'])
{
// code executed on the
// last iteration of the foreach loop
}
}

PHP Foreach If Array Last

foreach( $tabs2 as $tab2 => $name ){
$class = ( $tab2 == $current ) ? ' current' : '';
echo("<li class='posts'><a href='?page=pigg&tab=help&tab2=$tab2' class='$class'>$name");
echo(' |'); // If array last then do not display
echo('</a></li>');
}
I'm using a foreach loop to create a navigation for a WordPress plugin I'm working on, but I don't want the ' |' to be displayed for the last element, the code above is what I've got so far, I was thinking of using an if statement on the commented line, but not sure what the best approach would be, any ideas? Thanks!
The end() function is what you need:
if(end($tabs2) !== $name){
echo ' |'; // not the last element
}
I find it easier to check for first, rather than last. So I'd do it this way instead.
$first = true;
foreach( $tabs2 as $tab2 => $name ){
if ($first) {
$first = false;
} else {
echo(' | ');
}
$class = ( $tab2 == $current ) ? ' current' : '';
echo("<li class='posts'><a href='?page=pigg&tab=help&tab2=$tab2' class='$class'>$name</a></li>");
}
I also combined the last two echos together.
First thing you need to find out what is the last key of the array, and doing so by finding the array length, using the count() function.
Afterwords we gonna create a counter and add +1 on every loop.
If the counter and the last key are equal then it is the last key.
$last = count($array);
$counter = 1;
foreach ($array as $key => $val){
if ($counter != $last){
// all keys but the last one
// do something
$counter++; // add one to counter count
}
else {
// this is for the last key
}// end else
}// end foreach
I would do this way:
$arrLi = array();
foreach( $tabs2 as $tab2 => $name ){
$class = ( $tab2 == $current ) ? ' current' : '';
$arrLi[] = "<li class='posts'><a href='?page=pigg&tab=help&tab2=$tab2' class='$class'>$name</a></li>";
}
echo implode('|', $arrLi);
end() is good function to use
foreach( $tabs2 as $tab2 => $name ){
if(end($tabs2)== $name)
echo "|";
}
or you can do it manually for more understanding
$copyofarry = $tabs2;
$last = array_pop($copyofarry);
foreach( $tabs2 as $tab2 => $name ){
if($last == $name)
echo "|";
}
Something like this is possible:
$size = count($tabs2);
$counter = 0;
foreach( $tabs2 as $tab2 => $name ){
$class = ( $tab2 == $current ) ? ' current' : '';
echo("<li class='posts'><a href='?page=pigg&tab=help&tab2=$tab2' class='$class'>$name");
if ( ++$counter < $size ){
echo(' |'); // If array last then do not display
}
echo('</a></li>');
}
Why not pop the last element first? So you do not need to check if the current element is the last element in each iteration.
The function array_pop(&$array) returns the last element and removes it from the array.
<div id="breadcrumb">
<?php
$lastBreadcrumb = array_pop($breadcrumb);
foreach ($breadcrumb as $crumb){ ?>
<?php echo $crumb; ?>
<?php } ?><span><?php echo $lastBreadcrumb?></span>
</div>

loop through an array and show results

i m trying to do a loop but get stacked ,
i have a function that convert facebook id to facebook name , by the facebook api. name is getName().
on the other hand i have an arra with ids . name is $receivers.
the count of the total receivers $totalreceivers .
i want to show names of receivers according to the ids stored in the array.
i tried every thing but couldnt get it. any help will be appreciated . thanks in advance.
here is my code :
for ($i = 0; $i < $totalreceivers; $i++) {
foreach ( $receivers as $value)
{
echo getName($receivers[$i]) ;
}
}
the function :
function getName($me)
{
$facebookUrl = "https://graph.facebook.com/".$me;
$str = file_get_contents($facebookUrl);
$result = json_decode($str);
return $result->name;
}
The inner foreach loop seems to be entirely redundant. Try something like:
$names = array();
for ($i = 0; $i < $totalReceivers; $i++) {
$names[] = getName($receivers[$i]);
}
Doing a print_r($names) afterwards should show you the results of the loop, assuming your getNames function is working properly.
Depending of the content of the $receivers array try either
foreach ($receivers as $value){
echo getName($value) ;
}
or
foreach ($receivers as $key => $value){
echo getName($key) ;
}

Categories