I'm not sure if it's the proper title to use...
Here is my question.
I have stored table field names from a database in an array, and created a string like following
foreach ($fields as $field) {
$str.="<td>{$data[key][field]}</td>";
}
And I have stored the data from the table in a different array which is of the form
$data=array(array('name'=>"name 1",'address'=>"Address One"),array('name'=>"Name 2",'address'=>"Address two"),array('name'=>"Name 3",'address'=>"address three"),array('name'=>"test",'address'=>"test one"));
Now I have done the following
eval("\$str = \"$str\";");
foreach ($data as $key => $souceStr) {
?>
<tr>
<?=$str?>
</tr>
<?
}
?>
My aim is to replace the string that i have created from the first array with the values from the second array. I have seen coding in CMS like joomla where they replace '{somename}' with a value I want to do the same here.
=================================================
I'm sorry My question was not clear. But i got what i was looking for. Here is the code
<table width="100%" cellpadding="0" cellspacing="0" align="center" border="1">
<tr>
<?
foreach ($header as $val) {
?>
<th><?= $val ?></th>
<?
}
?>
</tr>
<?
foreach ($fields as $field) {
$str.='<td>$souceStr['.$field.']</td>';
}
foreach ($data as $key => $souceStr) {
eval("\$eval_str = \"$str\";");
?>
<tr>
<?php echo $eval_str; ?>
</tr>
<?
}
?>
The idea was to print a html table.
I don't think I completely understand what your question is, but what if you simply made a string from the second array just like you did from the first one? the result wold be the same, right?
Related
I have json html table in php, now i can't get it work that the output in the table will be near each other.
I am already few days busy with this, hope some one can help me.
<?php foreach($data2 as $row): ?>
<tr>
<td><?=$row['model'];?></td>
<td><?=$row['model2'];?></td>
</tr>
<?php endforeach;?>
My json output:
It looks like the JSON is not formatted for what you are trying to do. Every object has either modal or modal2, so the one that is not filled is undefined.
You should get the length of the longest list and use a normal for loop.
<?php ($index = 0; $index <= $lengthOfLongestList; $index++): ?>
<tr>
<td><?=$data2[index]['model'];?></td>
<td><?=$data2[index]['model2'];?></td>
</tr>
<?php endforeach;?>
I have been googling like crazy to find an answer to what I thought would have been a very common question to no avail...
I am using "\n" to break a table into a more readable structure when viewing source. Is there any way to get it to respect current indentation levels? For example:
Turn this:
<table>
<tbody>
<tr>
<td>Data</td>
<td>Data</td>
<td>Data</td>
<td>Data</td>
</tr>
</tbody>
</table>
Into this:
<table>
<tbody>
<tr>
<td>Data</td>
<td>Data</td>
<td>Data</td>
<td>Data</td>
</tr>
</tbody>
</table>
I am printing the tbody rows and cells out with the following code:
<?php
$first = true;
foreach ($data->rows as $row) {
if ($first) {
print "<tr class='highlight'>";
$first = false;
} else {
print "<tr>";
}
foreach ($row as $cell) {
print "<td>";
printf('%s', $cell);
print "</td>\n";
}
print "</tr>\n";
}
?>
<?php
$first = true;
foreach ($data->rows as $row) {
if ($first) {
echo "\t\t<tr class='highlight'>";
$first = false;
} else {
print "\t\t<tr>";
}
foreach ($row as $cell) {
print "\t\t\t<td>";
printf("\t\t\t\t%s", $cell);
print "</td>\n";
}
print "\t\t</tr>\n";
}
?>
I recommend you to write an identation counter, if you would like to do it dynamically. And remember to use double quotes for escape sequences, single quotes won´t work here (because it´s treated like a variable).
This is what google gave me.
You should concatinate the entire table in one php string, parse it through the function that can be found here:
http://www.daveperrett.com/articles/2007/04/05/format-xml-with-php/
and then simply echo $xml;
I just found it, I give no guarantee that this works as itended but it looks reliable.
The final HTML source have not to respect an indentation... Nobody see it (or you but don't get crazy with this).
Ok, sometimes this is also an obsession for me (one among many others ?), so you can do:
echo '
<tr>';
//Loop starts
echo '
<td></td>';
// Loop ends
echo '
</tr>';
Here you get a newline and your HTML indentation is independant from the PHP one.
Is it what you would ?
I have obtained an array output from a curl command. Now, I need to place that output in a table. I have written the entire code in php.
The .phtml part is:
echo "<table border='1'>
<tr><td>NAME</td></tr>
<tr><td>COUNTRY</td></tr>
</table>";
The loop part is:
foreach($arr['fruits'] as $key=>$fruit) {
?>
<tr><td><?php echo $fruit->NAME["Name"];}?></td></tr>
<tr><td><?php echo $fruit->COUNTRY["Country"];}?></td></tr>
I'm very very new to all this. So, I don't really know what I'm exactly doing. Thanks in advance...
Use it like this :
Considering your array structure is like this :
$your_array = array(array("name"=>"prasanth","country"=>"India"),
array("name"=>"bendra","country"=>"India"),
array("name"=>"User","country"=>"US")
);
<?php foreach($your_array as $key=>$fruit) { ?>
<tr><td><?php echo $fruit['name'];?></td></tr>
<tr><td><?php echo $fruit['country'];?></td></tr>
<?php } ?>
Here's all code.
<?php
echo "<table border='1'>
<tr><td>NAME</td></tr>
<tr><td>COUNTRY</td></tr>";
foreach($arr['fruits'] as $key=>$fruit) {
?>
<tr><td><?php echo $fruit->NAME["Name"];?></td></tr>
<tr><td><?php echo $fruit->COUNTRY["Country"];?></td></tr>
<?php ;}
echo "</table>";
?>
Your problem is with this sort of thing:
$fruit->NAME["Name"]
This means in the $fruit object look for a property called NAME that is an array containing the key "Name".
Also, your table isn't very tabular with only one cell per row. I would try something like this (if $fruit is really an array not an object):
<table border="1">
<tr><th>Name</th><th>Country</th></tr>
<?php
foreach( $arr['fruits'] as $fruit ) {
echo "<tr><td>$fruit['NAME']</td><td>$fruit['COUNTRY']</td></tr>";
}
?>
</table>
We can't help you without knowing the actual structure of $arr['fruits']
I have a simple working PHP script to write an HTML table from a text file that contains a single column of data that contains HTML links. This writes the data horizontally in a row across 5 or 6 columns as I want it to. But I am looking to set up a script with a loop that will take this list of data and input it into the table until it finishes the data list, so that I do not have to hard code each table cell individually. Just let the script create each table cell, at 5 or 6 columns across (whichever I need for this specific table), go to the next row, etc., until it runs out of data. The data in the data file will be added to on a regular basis, so the table will not be of a certain fixed length forever. I am using the echo command so that I can add some more HTML formatting later on.
Even though my existing script is simple and it works, if you can think of a better way of doing what I am trying to do, all suggestions are appreciated.
Thanks in advance, Stan...
PHP code follows:
<?php
$item = #fopen('linklist.txt', "r");
if ($item) { while (!feof($item)) { $lines[] = fgets($item, 4096); } fclose($item); }
echo'
<TABLE border="1">
<TR>
<TD>'.($lines[1]).'</td>
<TD>'.($lines[2]).'</td>
<TD>'.($lines[3]).'</td>
<TD>'.($lines[4]).'</td>
<TD>'.($lines[5]).'</td>
<TD>'.($lines[6]).'</td>
</tr>
<TR>
<TD>'.($lines[7]).'</td>
<TD>'.($lines[8]).'</td>
<TD>'.($lines[9]).'</td>
<TD>'.($lines[10]).'</td>
<TD>'.($lines[11]).'</td>
<TD>'.($lines[12]).'</td>
</tr>
<!-- And So On, And So On, ETC -->
</table>'
?>
<?php
echo '<table border="1"><tr>';
for($i=0; $i<sizeof($lines); $i++) {
echo '<td>'.$lines[$i].'</td>';
if(($i+1)%6==0 && $i!=sizeof($lines)-1) echo '</tr><tr>';
}
echo '</tr></table>';
?>
Explanation:
Repeats through each "line" and writes the <td>value</td>
If a line is a multiple of 6, after writing the value, then close the row, and open another (unless it's the last one, since it will close the row after the loop as well.
(I assume you meant to start on $line[0], but if you really meant to start on $line[1], just change the $i=0; to $i=1;, remove the +1 in the row check, and change $i<sizeof to $i<=sizeof
$lines = chunk_split($lines,6);
?>
<TABLE border="1">
<? foreach ($lines as $row): ?>
<TR>
<? foreach ($row as $value): ?>
<TD><?=$value?></td>
<? endforeach ?>
<TR>
<? endforeach ?>
</TABLE>
In pseudo code...
x = 0
echo '<TABLE border="1">'
For each $line in $lines {
x = x + 1
if x = 1 {
echo '<TR>'
}
echo <TD>'.($line).'</TD>
if x = 6 {
echo '</TR>'
x = 0
}
}
echo '</TABLE>'
Note the use of the $line object to hold the value of the $line array element.
hth
If you use a loop, you can also avoid reading the complete file into memory, which might be beneficial:
<?php
$item = #fopen('linklist.txt', "r");
if ($item) {
echo'<TABLE border="1">';
$i=0;
$lines=array();
while (!feof($item)) {
$line[] = fgets($item, 4096);
$i++;
if ($i==6) {
echo "<tr>";
echo '<TD>'.($lines[0]).'</td>';
echo '<TD>'.($lines[1]).'</td>';
echo '<TD>'.($lines[2]).'</td>';
echo '<TD>'.($lines[3]).'</td>';
echo '<TD>'.($lines[4]).'</td>';
echo '<TD>'.($lines[5]).'</td>';
echo "<tr>";
$i=0;
$lines=array();
}
}
echo '</table>';
fclose($item);
}
?>
The code loop an array and display all views for a user. Now things changed and I just need to display one result from a foreach loop. How do I do that?
<table class="report_edits_table">
<thead>
<tr class="dates_row">
<?php foreach($report['edits'] as $report_edit) : ?>
<td colspan="2" report_edit_id="<?php echo $report_edit['id'] ?>"><div class="date_container">
<?php if($sf_user->hasCredential(Attribute::COACHING_EDIT_ACCESS)) : ?>
<span class="ui-icon ui-icon-trash">Remove</span>
<?php endif?>
<?php echo "View " . link_to($report_edit['created'], sprintf('coaching/viewReportEdit?reportedit=%s', $report_edit['id']), array('title' => 'View This Contact')) ?> </div></td>
<?php endforeach ?>
</tr>
</thead>
<tbody>
<?php foreach($report['edits_titles'] as $index => $title) : ?>
<tr class="coach_row">
<?php for ($i=max(0, count($report['edits'])-2); $i<count($report['edits']); $i++) : $report_edit = $report['edits'][$i] ?>
<td class="name_column"><?php echo $title ?></td>
<td class="value_column"><?php echo $report_edit[$index] ?></td>
<?php endfor ?>
</tr>
<?php endforeach ?>
</tbody>
Use the break command for simple conversion:
<?php for ... ?>
... stuff here ...
<?php break; ?>
<?php endfor ... ?>
A better solution would be to remove the foreach completely.
It sounds like you want to grab the first element from an array without having to loop through the rest of them.
PHP provides a set of functions for situations like this.
To get the first element in an array, start off using the reset() function to position the array pointer to the start of the array, then use the current() function to read the element that the pointer is looking at.
So your code would look like this:
<?php
reset($report['edits']);
$report_edit = current($report['edits']);
?>
Now you can work with $report_edits without having to use a foreach() loop.
(note that the array pointer does actually start by default at the first record, so you could skip the reset() call, but it's best practice not to do that because it might have been changed elsewhere in your code without you realising it)
If you want to move on to the next record after that, you can use the next() function. As you can see, if you wanted to, it would theoretically be possible to use these functions to write an alternative type of foreach() loop. There wouldn't be any point in using them them that way, but it's possible. But they do allow more fine-grained control over the array, which is handy for situations like yours.
Hope that helps.
Plenty of ways
Access the index of the array element in question directly
Update whatever logic fetches/generates the array to only return the element of interest
Use a for loop that terminates after a single loop
array_filter your array to get the element of interest
Break at the end of your foreach loop so it terminates after the first iteration
Conditionally check your index in the foreach loop and only output markup if the index matches the element of interest
And so on
I'd recommend just getting the array element of interest (number 2 on the list) as it means less data bouncing around your code (and probably between your PHP box and the database if you're populating the array from an SQL server)
Simplest method?
Place a break as the last line of your foreach. It'll execute once, then quit. (As long as which element you stop on is of no importance).
Secondary method: use array_pop or array_shift on your $report['edits'] or $report['edits_titles'] to get on element, lose the for loop, and reference the element you just retrieved.
For example:
//
// current
//
foreach ($report['edits'] as $report_edit) :
/* markup */
endforeach;
//
// modified version
//
$report_edit = array_shift($report['edits']);
/* markup */
Use <?php break ?> before <?php endforeach ?>
example ::
<?php
foreach ($this->oFuelData AS $aFuelData ) {
echo $aFuelData['vehicle'];
break;
}
?>
You can also use it for reference
foreach($array as $element) {
if ($element === reset($array))
echo $element;
if ($element === end($array))
echo $element;
}