How do I put the first foreach statement's output in one column in a table and the other foreach statement's output in another column. I tried something but it put it all in one column for some reason. Here is my code:
<table border="0" align="center">
<?php
foreach($anchors as $a) {
$text = $a->nodeValue;
$href = $a->getAttribute('href');
$i++;
if ($i > 16) {
if (strpos($text, "by owner") === false) {
if (strpos($text, "map") === false) {
echo "<tr><td><a href =' ".$href." '>".$text."</a><br/></td></tr>";
}
}
}
foreach($span as $s) {
echo "<tr><td>".$s->nodeValue."</td></tr>";
}
}
?>
</table>
<tr></tr> marks a row. <td></td> marks a column. To make 2 columns, use just one set of <tr> tags per iteration, with two sets of <td></td>s between them.
That said, what exactly is $span? Does it contain the same number of elements as $anchors, and you want to display one item from each per row? If so you'll need to restructure your code a bit. There are several ways to do this—here's a simple way:
<table border="0" align="center">
<?php
$i = 0;
foreach($anchors as $a) {
echo "<tr>";
$text = $a->nodeValue;
$href = $a->getAttribute('href');
if ($i >= 16) {
if (strpos($text, "by owner") === false) {
if (strpos($text, "map") === false) {
echo "<td><a href =' ".$href." '>".$text."</a><br/></td>";
}
}
} else {
echo "<td></td>"; #output a blank cell in the first column
}
echo "<td>" . $span[$i]->nodeValue . "</td>";
echo "</tr>";
++$i
}
?>
</table>
EDIT: It looks like your $span is a DOMNodeList object, not an array. I don't have experience with this, but it looks like you can use the DOMNodelist::item function to get the current item in the list (see http://php.net/manual/en/domnodelist.item.php):
echo "<td>" . $span->item($i)->nodeValue . "</td>";
So try changing the respective line in my answer to that.
It is hard without an idea of the data, but something like this perhaps:
// start a table
echo '<table>';
// for as long as there are elements in both span and anchors
for ($i=0; $i < $anchors->length && $i < $span->length; $i++) {
// start a new table row
echo '<tr>';
// get the current span and anchor
$a = $anchors->item($i);
$s = $span->item($i);
// print them
$text = $a->nodeValue;
$href = $a->getAttribute('href');
// col 1, number
echo '<td>'.$i.'</td>';
// col 2, anchor
echo '<td>'.$text.'</td>';
// col 3, span
echo '<td>'.$s->nodeValue.'</td>';
// close the table row
echo '</tr>';
}
// close the table
echo '</table>';
(code not tested) It is difficult to be more specific without the actual data.
This uses the 'current' and 'next' built in to php.
A few hints/remarks/sidenotes that may help you on the way:
- Note that I used single quotes cause they are much better for
performance (double quotes will be interpreted by php).
- Try to use as little loops (for, while, foreach) as possible. They are a powerfull
tool, but can drain memory and performance quickly!
- Only nest loops if you are working with multiple dimensions (array inside array),
which is not the case here (I think)
- Try to limit the number of nested blocks (if inside if inside if inside loop). I try to go never deeper then 2 levels (which is not an absolute rule off course, just a good standard). If not possible create a function.
- Comment your code! I have difficulty understanding your code (and I write PHP daily for a living), and I can imagine you will to in a couple of weeks. Commenting may look like a waste of time, but it will ease debugging a lot, and is a blessing when updating your (or someone elses) code later on!
EDIT:
I just noticed you are not working with a DOMNodeList and not an array, so I updated my code. Should work fine, and a lot cleaner code imo. Like I said, hard without seeing the data...
Related
I have a feeling I'm going to get scolded for this but here is the question.
$seq_numbers = range('1', '24');
foreach($seq_numbers as $seq_number)
{
Bullet <?php echo $seq_number;?>
// (this successfully creates - Bullet 1, Bullet 2, etc. -
below is the problem.
<?php echo $db_rs['bullet_($seqnumber)'];?>
} // this one doesn't work.
I've tried
with curly brackets {}
I basically have a few columns that are named same except for number at the end (bullet_1, bullet_2, bullet_3, etc.) and want to get the results using a loop.
Your problem is, that PHP doesn't replace variables inside strings enclosed with single quotes. You need to use $db_rs["bullet_{$seq_number}"] or one of those:
<?php
foreach ($seq_numbers as $seq_number) {
$key = 'bullet_' . $seq_number;
echo $db_rs[$key];
}
Even shorter, but a little less clear:
<?php
foreach ($seq_numbers as $seq_number) {
echo $db_rs['bullet_' . $seq_number];
}
An entirely different approach would be to loop over the result array. Then you don't even need $seq_numbers. Just as an afterthought.
<?php
foreach ($db_rs as $key => $value) {
if (substr($key, 0, 7) == 'bullet_') {
echo $value;
}
}
Oh...and watch out for how you spell your variables. You are using $seq_number and $seqnumber.
<?php echo $db_rs['bullet_'.$seqnumber];?>
why not:
$db_rs['bullet_'.$seqnumber]
If not, what are your fields, and what does a var_dump of $db_rs look like?
try this...
$seq_numbers = range('1', '24');
foreach($seq_numbers as $seq_number)
{
Bullet <?php echo $seq_number;?>
// (this successfully creates - Bullet 1, Bullet 2, etc. -
below is the problem.
<?php echo $db_rs["bullet_($seqnumber)"];?>
} // now it works.
I'm trying to figure out if I need to do this inside the for loop or outside the for loop but I want to check to see its empty or not first.
echo "<ul>";
for($x = 0; $x <= (count($quotesArray)-1); $x++)
{
echo "<li>".stripslashes($quotesArray[$x]->quote)."</li>";
}
echo "</ul>";
There is something simpler that checking during loop - it filters all the values and is called array_filter() function:
$quotesArray = array_filter($quotesArray);
echo "<ul>";
foreach($quotesArray as $quote){
echo "<li>".stripslashes($quote)."</li>";
};
echo "</ul>";
The above assumes that $quotesArray contains strings (or elements that work correctly in string context) and you do not want only the elements that are evaluated as false when converted to boolean (see more about converting to boolean).
Additionally you can simplify your code further:
$quotesArray = array_filter($quotesArray);
$quotesArray = array_map('stripslashes', $quotesArray);
echo '<ul><li>'.implode('</li><li>', $quotesArray).'</li></ul>';
if you know $quotesArray contains at least one element.
EDIT:
Short version, that also checks whether the list should be generated (in other words: whether array contains at least one element after processing):
$quotesArray = array_map('stripslashes', array_filter($quotesArray));
if (!empty($quotesArray)) {
echo '<ul><li>'.implode('</li><li>', $quotesArray).'</li></ul>';
};
It needs to be outside the loop because if it is empty, and you don't generate any list items, then you have no list, so you should not generate the ul start and end tags either (since a list with no list items is invalid).
well if you dont wan the list at all then you should do it before the echoing of the first <ul>
if(count($quotesArray) > 0){
//Do your echos and loops in here
}
You can just run both checks.
if($quotesArray){
echo '<ul>';
foreach ($quotesArray as $quote) {
if ($quote) {
echo '<li>' . stripslashes($quote->quote) . '</li>';
}
}
echo '</ul>';
}
When you say you want to check if it's empty, do you mean the entire $quotesArray or one of the values within it?
If you mean you want to check if a value within the array is empty, you could consider this approach:
echo '<ul>';
foreach ($quotesArray as $quote) {
if ($quote) {
echo '<li>' . stripslashes($quote) . '</li>';
}
}
echo '</ul>';
for($j = 0; $j < $length; $j++){
while($answersRow = mysql_fetch_row($fetch)){
if($answersRow[0] == $curr_answer_id[$j]){
echo "<input type='checkbox' value='$answersRow[0]' checked>$answersRow[1]</input> ";
} else {
echo "<input type='checkbox' value='$answersRow[0]'>$answersRow[1]</input> ";
}
}
}
Assuming $fetch is my result, here's my dilemma. The for loop represents the array of checkboxes. The first loop around, everything works fine. However, any more than that, we no longer cycle through the while loop because of the internal mysql pointer. I know I can move the pointer around using mysql_data_seek(), but don't have an idea on how to do so usefully. If I move it back to 0, then it just outputs everything for as many things that were checked.
I basically want to traverse through for each question through the database but without any overlap. It is a bit hard to explain so I apologize if I am not explaining this simple problem properly; I'll try and clarify if need be.
You can save the results of your first while in an array:
//> FIRST LOOP
while($row = mysql_fetch_assoc($query)) {
$rows[] = $row; //> Saving in the $rows array
//> All your code from your first loop
}
//> SECOND LOOP
foreach($rows as $v) {
//> All your code you need for your second loop without any additional query
}
Also sorry If I misunderstood your question but It is not so clear what you are asking for
Addendum
After reading better your question if I understood correctly you want to achive everything within only one loop. In this case you can save the html you need in the first while like this:
$firstLoop = '';
$secondLoop = '';
while() {
$firstLoop .= '<option> [...]';
$secondLoop .= '<div> [...]';
}
At this point with one loop you have built the html you need and they are in $firstLoop and $secondLoop. This is of course faster then any other solutions
Is there a way to only print or output 10 elements per row inside a table in PHP from an indexed array with X number of elements of type int.
Maybe some function, I have not heard of?
Or some technique that's used by professionals or beginners alike.
I will embed some code for the TR and TD; however, I was just wondering if there is something I could use to only have 10 elements per row inside of my table.
[Disclaimer: I am new to PHP, and I am just learning, so please no flamers, it really hinders the learning process when one is trying to find solutions or information, thank you.]
You can use a counter in your loop to keep track of how many <td> elements you have generated in the current row:
echo "<tr>";
$i = 0;
foreach (...)
{
if ($i++ % 10 == 0)
{
echo "</tr><tr>";
}
echo "<td></td>";
}
echo "</tr>";
I like using: foreach, array_chunk, and implode to do this. It's better than having to futz with incrementing variables. I suggest you review array basics -- it's powerful stuff.
// here's an array with integers 1 to 50, for example:
$your_array = range(1,50);
// set how many you want in each row
$per_row = 10;
print "<table cellspacing='0' cellpadding='2' border='1'>\n";
Here's the code you can drop in to replace what you have:
foreach (array_chunk($your_array, $per_row) as $set_of_numbers) {
print "<tr><td>";
print implode('</td><td>',$set_of_numbers);
print "</td></tr>\n";
}
And finish with:
print "</table>\n";
That should get you the output you describe, a set of integers in a table, with 10 items per row. Now, if the size of $your_array has a remainder when divided by 10, you may need to pad those cells for looks, but that's secondary.
Output:
<table cellspacing='0' cellpadding='2' border='1'>
<tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td><td>8</td><td>9</td><td>10</td></tr>
<tr><td>11</td><td>12</td><td>13</td><td>14</td><td>15</td><td>16</td><td>17</td><td>18</td><td>19</td><td>20</td></tr>
<tr><td>21</td><td>22</td><td>23</td><td>24</td><td>25</td><td>26</td><td>27</td><td>28</td><td>29</td><td>30</td></tr>
<tr><td>31</td><td>32</td><td>33</td><td>34</td><td>35</td><td>36</td><td>37</td><td>38</td><td>39</td><td>40</td></tr>
<tr><td>41</td><td>42</td><td>43</td><td>44</td><td>45</td><td>46</td><td>47</td><td>48</td><td>49</td><td>50</td></tr>
</table>
I'm trying, but I'm stucked with the logic... so, I have this:
$max_items=10;
echo '<table>';
echo '<tr>';
foreach ($feed->get_items(0, $max_items) as $item):
echo '<td>';
echo $some_value;
echo '</td>';
endforeach;
echo '</tr>';
echo '</table>';
I want to show the results like this:
[1][2]
[3][4]
[5][6]
[7][8]
[9][10]
I have to use a while statement? A for loop? Inside or outside the foreach code?
I really don't get it...
Thanks for any kind of help
Here's a very simple example of how to do this sort of HTML building.
<?php
$data = range( 'a', 'z' );
$numCols = 2;
echo "<table>\n";
echo "\t<tr>\n";
foreach( $data as $i => $item )
{
if ( $i != 0 && $i++ % $numCols == 0 )
{
echo "\t</tr>\n\t<tr>\n";
}
echo "\t\t<td>$item</td>\n";
}
echo "\t</tr>\n";
echo '</table>';
This way, you can change $numCols to be 3 or 4 (or any number) and always see that number of columns in the output, and it does so without using an nested loop.
Take a look at this link to Displaying Recent Posts On a Non-WordPress Page. I think what you may be looking for is a way to loop over the objects get methods. For that you will need a nested loop and some sort of reflection.
I was just recently working with SimplePie on the February release of Cogenuity so this is still fresh in my mind.
Your $some_value variable never gets initialized.
The $item object will have such methods as get_permalink(), get_title(), get_description(), and get_date()