July 5, 2013

PHP foreach multiple results

User2553099’s Question:

I´m not an advanced php coder so I need some help here.

I´m trying to echo list items with a link pointing to the full image and the thumnail.

This is the desired result:

<li>
    <a href="fullimagepath1">
        <img src="thumnailpath1" />
    </a>
</li>
<li>
    <a href="fullimagepath2">
        <img src="thumnailpath2" />
    </a>
</li>
<li>
    <a href="fullimagepath3">
        <img src="thumnailpath3" />
    </a>
</li>
...

This is the code I’m using

    <?php
        $images = rwmb_meta( 'product_gallery', 'type=image&size=press-thumb' );
    $fullimages = rwmb_meta( 'product_gallery', 'type=image&size=productfull-thumb' );
            foreach ( $fullimages as $fimages)
            foreach ( $images as $image)
                {
                    echo "<li><a class='thumb' href='{$fimages['url']}'><img src='{$image['url']}' /></a></li>";

    } ?>

The problem is that I’m getting the thumbnails but multiplied by the number of real results. If I have 3 thumbnails for my gallery the result will be 9 thumbnails, if I have 5 will get 25.

How can I fix the code?
Thanks in advance!

This is because of this line foreach ( $fullimages as $fimages) which is triggering inner loops.

Since you probably have 3 images and both array hold three items array, loop will run 3 times inside a bigger loop which will also execute 3 times. So you have 9 items.

On your code

foreach ( $fullimages as $fimages) //Because of this loop next statement executes
foreach ( $images as $image) {
  echo "<li><a class='thumb' href='{$fimages['url']}'><img src='{$image['url']}' /></a></li>";
}

What you probably want is?

foreach ( $fullimages as $k => $fimages) {
                      // ^ Get the index of the array
  echo "<li><a class='thumb' href='{$fimages['url']}'>
       <img src='{$images[$k]['url']}' /></a></li>";
                       // ^ Use that key to find the thumbnail from $images array
}
March 8, 2013

Jquery Looping through elements created at runtime

Question by dev_darin

i have a list that is passed to a page and the elements are created at runtime. I would like to loop through these elements and preform some action for each element. Under is my code:
for each person that gets created from this list i would like to preform a check on that person. Can someone help me i am only getting the check happening once:

jQuery:

$(document).ready(function() {

    $("#userId").each(function(i){
        if ($("#userId").val != '') {
            alert('not null' + i);
        }
    });                 
});

JSP:

<c:forEach items="${person}" var="person">

<input= type="text" id="userId" value="${person.userid}" />
    First name:- ${person.fName} , Last Name:- ${person.lName}
</c:forEach>

Answer by Andbdrew

you cannot have multiple elements on a page with the same id attribute. try using classes instead.

try something like:

$(document).ready(function() {

   $(".userId").each(function(i){
       if ($(this).val() != '') {
           alert('not null' + i);
       }
   });
});

Another thing to note is that .val is a method, so you need to call it to get the value. Use .val() instead of .val. As you have your code now, $(selector).val is a function, so it will never be the empty string you are testing it against.

Also your JSP should be something like:

<c:forEach items="${person}" var="person">

<input= type="text" class="userId" value="${person.userid}" />
    First name:- ${person.fName} , Last Name:- ${person.lName}
</c:forEach>

Answer by Starx

Your loop will create multiple element with same ID, first change that. It is better to use class names instead.

<c:forEach items="${person}" var="person">

    <input= type="text" class="user" id="userId-${person.userid}" value="${person.userid}" />
       <!--             ^ Use Class &  ^ Id to uniquely identify the user -->
       First name:- ${person.fName} , Last Name:- ${person.lName}
</c:forEach>

Next you can use .find() to find even the dynamically generated element. But I recommend using my solutions using the class attribute.

$(".user").each(function(i) {
    if ($(this).val() != '') {
          alert('not null' + i);
    }
});
March 5, 2013

Why are my variables not interpolated inside strings?

Question by peace

<?php 

$array = array('1' => 'one', '2' => 'two','3','three');

foreach($array as $num => $number){
    echo 'Numburic: $num <br /> Number: $number';
};

?>

The result I’m looking for:

1. one
2. two
3. three

Answer by Starx

For that output, you have to do:

foreach($array as $num => $number){
    echo "$num. $number <br />";
};

Your mistakes as pointed in other answers is using a single quotes to wrap your string with a PHP variable inside. Only when you use " (double quotes) your variables will be parsed by PHP.

Also your array definition is wrong (Credit: Musa’s Comment). Change

$array = array('1' => 'one', '2' => 'two','3', 'three');
                                        // ^ This is a separate array item 
                                        //   not its index

To

$array = array('1' => 'one', '2' => 'two','3' => 'three');
May 4, 2012

Foreach loop only looping once?

Question by myladeybugg

I’m having trouble with my foreach loop opening multiple files.

My foreach loop is only running once for the first item number. The foreach loop runs then goes to the “api.php” page but then stops and doesn’t go back to the foreach loop to get the next item number. How do I tell it to go through all of item numbers in my database?

Would I use cURL somehow?

Thanks

Here’s my code:

$itemnumber = array("".$result['item_number']."");

foreach ($itemnumber as $item_number) {

echo "<form method="post" action="api.php" name="ChangeSubmit" id="ChangeSubmit">";
echo "<input type="text" name="item_number" value="{$item_number}" />";

echo "<script type="text/javascript">
function myfunc () {
var frm = document.getElementById("ChangeSubmit");
frm.submit();
}
window.onload = myfunc;
</script></form>";



}

Answer by Starx

You actually have only one item in your array. SO it is looping only once.

Your code $itemnumber = array("".$result['item_number'].""); will translate to

 $itemnumber = array($result['item_number']);

Because, the double double-quotes you provided have no significance in the code too. SO, at last the array will have only one item.

April 18, 2012

Printing UL LI nested in Foreach Loop

Question by HardCode

i have an array structure like

[members] => Members List | 26
[member.php?id=3] => John | 26-26 
[member.php?id=4] => Alice | 26-26 
[member.php?id=5] => Michel | 26-26 
[news] => News details | 45
[alerts] > Alerts | 32

i traverse this using foreach loop. i want to print the Whole list as UL LI. The Members List will be an LI but when its childs comes (memeber.php?id=*) etc then it should inherit UL LI. I want the child to be in a nested LIs

CODE

$counter = 0;
foreach($array as $key => $values)
{
     if($counter == 0)
        {
            echo "<ul>";
        }
    if($key != "" && $key != "END")
        {
            echo "<li>".$values."</li>";
        }
    if($key == "END")
        {
            echo "</ul>";
        }
    $counter++;    
}

Answer by Muhammad Alvin

I don’t know exactly the problem you have. But i think, you want something like this:

<ul>
    <li>
        <a href="members">Members List</a>
        <ul>
            <li><a href="member.php?id=3">John</a></li>
            <li><a href="member.php?id=4">Alice</a></li>
            <li><a href="member.php?id=5">Michel</a></li>
        </ul>
    </li>
    <li><a href="news">News details</a></li>
    <li><a href="alerts">Alerts</a></li>
</ul>

If yes, then i suggest you to change your array structure. Array can also be nested. And it will be easier if you have something like this:

$data = array(
    array('members', 'Members List', array(
        array('member.php?id=3', 'John'),
        array('member.php?id=4', 'Alice'),
        array('member.php?id=5', 'Michel'),
    )),
    array('news', 'News details'),
    array('alerts', 'Alerts')
);
  • $data is array.
  • Items in $data is array with at least 2 items. 1st item is href/url,
    2nd item is label/text. If it has 3rd item, then it will be the
    children (subitems).
  • Subitems is composed similar to items, where 1st item is href/url, 2nd
    item is label/text.

Then, the following code will convert it to HTML:

echo '<ul>';
foreach ($data as $item) {
    // $item[0] -> href/url, $item[1] -> label/text, $item[2] -> subitems
    echo '<li>';
    echo '<a href="' . $item[0] . '">' . $item[1] . '</a>';

    if (isset($item[2])) { // if this item has subitems...
        echo '<ul>';
        foreach ($item[2] as $subitem) {
            // $subitem[0] -> href/url, $subitem[1] -> label/text
            echo '<li><a href="' . $subitem[0] . '">' . $subitem[1] . '</a></li>';
        }
        echo '</ul>';
    }

    echo '</li>';
}
echo '</ul>';

Answer by Starx

Your script is not working, because you have referenced the URLs as $key, but still accessing them using $url inside your loop.

Here is how you should do it.

$counter = 0;
foreach($array as $url => $values)
{
     if($counter == 0)
        {
            echo "<ul>";
        }
    if($url != "" && $url != "END")
        {
            echo "<li>".$values."</li>";
        }
    if($url == "END")
        {
            echo "</ul>";
        }
    $counter++;    
}

But a simple way to create the list from your array is this

//First remove the END key from the array, is not needed


echo "<ul>";
foreach($array as $link => $value) {
   //THERE is no way $link can be ""
   echo "<li><a href="$link">$value</a></li>";
}
echo "</ul>";
April 9, 2012

set key and values on array

Question by user983248

I have on array like:
$myarray = array("color", "red", "size", "big", "flavor", "bitter"); where color, size and flavor are the keys and the other are the values. How can I loop true the values only on the array.

I have a few arrays like that one so I only need to create a table and display their values like:

<table>
 <thead>
  <tr>
   <th>Color</th>
   <th>Size</th>
   <th>Flavor</th>
  </tr>
 </thead>
 <tbody>
       // I'm stuck here because I don't know how to get the values of each array
 </tbody>
</table>

Any help will be appreciated
Thanks

Answer by deceze

while (list(, $key) = each($array)) {
    $value = current($array);
    next($array);

    echo $key, ': ', $value, PHP_EOL;
}

But yes, you should really use a proper associative array instead of this makeshift solution.

Answer by Starx

You are defining array incorrectly.

$myarray=array(
    'color'=>'red',
    'size'=>'big',
    'flavor'=>'bitter'
);

Then use it with foreach

foreach($myarray as $key => $value) {
   echo $key; //echoes the indexes like color
   echo $value; //echoes values like red
}
April 2, 2012

for each loop exception

Question by oneofthelions

I get an exception in my second print line.

int num[] = {50,20,45,82,25,63};
System.out.print("Given number : ");
for(int d:num){
System.out.print("  " + num[d]);
}

The console output is

Given number : Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 50

Why doesn’t d take all the array elements but only 50?

Answer by Starx

In the for(int d:num) loop every item is represented by d not num[d]

So, here is how it should be done.

for(int d:num){
    System.out.print("  " + d);
}

A simple dry run will show you where you went wrong.

For the first loop your statement will come down to num[50] which is not available anywhere, so you get the exception.


However, if your attempt was to use indexing, then a simple trick below will do the trick

int index = 0;
for(int d:num){
    System.out.print("  " + num[index++]);
}

But I honestly believe, this is not the correct solution to the problem.

March 12, 2012

two foreach loops combined for email sending

Question by Bowser Entertainment

I am trying to take a two text areas with multiple emails, one with the “from” emails, and one with the “to” emails. Combine the emails line by line and send emails out accordingly.

Ex:

“To” list:

        mike@gmail.com

        nick@hotmail.com

        adam@yahoo.com

“From” list:

        ashley@gmail.com

        brittney@yahoo.com

        racheal@hotmail.com

I want a email sent to:

   mike@gmail.com from ashley@gmail.com

   nick@hotmail.com from brittney@yahoo.com

   adam@yahoo.com from racheal@hotmail.com

Any help would be greatly appreciated. Thanks in advanced.

Below is the script I got so far, It sends to multiple emails from one email.

 <?php
 if (isset($_POST['submit']))
 {

    // Execute this code if the submit button is pressed.
    $raw_email_account = $_POST['email_from'];
    $email = $_POST['email_to'];
    $sent = "";
    $invalid = "";

    //Separating each line to be read by foreach
    $list = explode("n",$email);

    //Rendering the separeted data from each line
    foreach($list AS $data) {
                //Separating each line to be read by foreach
            $item = explode(":",$data);
            $mail_body = '<html><body>email here</body></html>';
                $subject = "subject here";
                $headers  = "From:".$raw_email_account."rn";
                $headers .= "Content-type: text/htmlrn";
                $to = $item[0];

                $mail_result = mail($to, $subject, $mail_body, $headers);

            if ($mail_result) {
               $valid++;
            } else {
                   // write into an error log if the mail function fails
                   $invalid++;
            }
    }

}
?>
<html>
<head>
</head>
<body>
<form action="email_sender.php" method="POST">
<div align="center">From Email Accounts: <textarea name="email_from" cols="100"    rows="60"></textarea></div><br />
<div align="center">To Email Accounts: <textarea name="email_to" cols="100" rows="60">        </textarea></div><br />
<div align="center"><input type="submit" name="submit"></div>
<br>
Valids: <?php echo $valid;?>
<br>
Invalids: <?php echo $invalid;?>
</body>
</html>

Answer by Vitalmax

Add logic that provides same count of $email and $raw_email_account arrays before foreach loop.

$list = explode("n",$email);
$list2 = explode("n", $raw_email_account);

foreach($list AS $key=>$data) {
            ...
            $headers  = "From:".$list2[$key]."rn";
            ...
}

Answer by Starx

If the array is by default, the indexes will coincide. So you can do something like this.

$toList = array(..);
$fromList = array(...);

foreach($toList as $key => $value) {
    $toAddress = $value;
    $fromAddress = $fromList[$key]; 
    //..
    //.. Go on with you mail function
}
...

Please fill the form - I will response as fast as I can!