I have a PHP array from a submitted form that looks like the following
$form_data = Array (
[input_1_1] => Product Name
[input_1_2] => $8.00
[input_1_3] => 2
[input_2_1] => Other Product Name
[input_2_2] => $3.50
[input_2_3] => 8
)
I am looking for the best way to parse this so I can build something markup like this:
<table>
<tr>
<td>Product Name</td>
<td>$8.00</td>
<td>2</td>
</tr>
<tr>
<td>Other Product Name</td>
<td>$3.50</td>
<td>8</td>
</tr>
</table>
What would be most kosher way to do this?
Should I split this array into smaller arrays based on the 1st number (and then loop them)?
Alternatively should I just build the markup based on sets of three, like:
<table>
<tr>
<td><?php echo $form_data[1]; ?></td>
<td><?php echo $form_data[2]; ?></td>
<td><?php echo $form_data[3]; ?></td>
</tr>
<tr>
<td><?php echo $form_data[4]; ?></td>
<td><?php echo $form_data[5]; ?></td>
<td><?php echo $form_data[6]; ?></td>
</tr>
</table>
Any help/advice appreciated.
take a look on this example: http://codepad.org/zhKbc4p1
$arr = array('input_1_1'=>'Name', 'input_1_2'=>'$8', 'input_1_3'=>1, 'input_2_1'=>'Name', 'input_2_2'=>'$28', 'input_2_3'=>1);
$chunk = array_chunk($arr, 3);
print_r($chunk);
foreach( $chunk as $val ){
foreach($val as $v){
echo $v . "\r\n";
}
echo "\r\n\r\n";
}
Expected HTML format:
foreach( $chunk as $val ){
echo "<tr>";
foreach($val as $v){
echo "<td>" . $v . "</td>";
}
echo "</tr>";
}
$last_group = '';
foreach ($form_data as $key => $value) {
preg_match('/input_(\d+)/', $key, $match);
if ($match[1] != $last_group) {
if ($last_group) {
echo "</tr>\n";
}
echo "<tr>\n";
$last_group = $match[1];
}
echo "<td>$value</td>\n";
}
if ($last_group) {
echo "</tr>\n";
}
It would be better to structure your form like this, though:
<input type="text" name="name[]">
<input type="text" name="price[]">
<input type="text" name="quantity[]">
Then the $_POST['name'], $_POST['price'] and $_POST['quantity'] will be arrays, and you can iterate over them:
foreach ($_POST['name'] AS $i => $name) {
$price = $_POST['price'][$i];
$quantity = $_POST['quantity'][$i];
// Output the table row
}
Assuming each table row has 3 elements each;
<?php
echo "<table>
<tr>";
$form_data = Array (
"input_1_1" => "Product Name",
"input_1_2" => "$8.00",
"input_1_3" => "2",
"input_2_1" => "Other Product Name",
"input_2_2" => "$3.50",
"input_2_3" => "8"
);
$intRowBefore = 1;
foreach( $form_data as $strKey => $strVal ) {
$intRow = explode("_", $strKey)[1];
if( $intRowBefore != $intRow ) {
echo "</tr><tr>";
$intRowBefore = $intRow;
}
echo "<td>". $strVal ."</td>";
}
echo "</tr></table>";
Consider
<?php
$form_data = array();
$form_data['input_1_1'] = 'Product Name';
$form_data['input_1_2'] = '$8.00';
$form_data['input_1_3'] = '2';
$form_data['input_2_1'] = 'Other Product Name';
$form_data['input_2_2'] = '$3.50';
$form_data['input_2_3'] = '8';
// Get unique keys
function get_unique_keys($keys)
{
$arr = array();
foreach($keys as $k=>$v){
$arr[] = substr($k, 0, strlen($k)-2);
}
return array_unique($arr);
}
$keys = get_unique_keys($form_data);
// Output
printf("<table>\n");
foreach($keys as $k)
{
printf(" <tr>\n");
printf(" <td>%s</td>\n", $form_data[$k.'_1']);
printf(" <td>%s</td>\n", $form_data[$k.'_2']);
printf(" <td>%s</td>\n", $form_data[$k.'_2']);
printf(" </td>\n");
}
printf("</table>\n");
Which outputs:
<table>
<tr>
<td>Product Name</td>
<td>$8.00</td>
<td>$8.00</td>
</td>
<tr>
<td>Other Product Name</td>
<td>$3.50</td>
<td>$3.50</td>
</td>
</table>
See it in action: http://ideone.com/355STr
It's not super complicated. It gets the key "roots" we'll call them (input_1, input_2, etc) and loops over those, appending the additional _1,_2,_3 when needed.
A better solution long-term would be to redesign the form, but that's not always a possibility.
Try This
$form_data = Array (
'[input_1_1]' => 'Product Name',
'[input_1_2]' => '$8.00',
'[input_1_3]' => '2',
'[input_2_1]' => 'Other Product Name',
'[input_2_2]' => '$3.50',
'[input_2_3]' => '8'
);
echo "<table>";
foreach($form_data as $k=>$v)
{
echo "<tr>";
echo "<td>".$v."</td>";
echo "</tr>";
}
echo "</table>";
<?php
$form_data = array(
'input_1_1' => 'Product Name',
'input_1_2' => 8.00,
'input_1_3' => 2,
'input_2_1' => 'Other Product Name',
'input_2_2' => 3.50,
'input_2_3' => 8
);
end($form_data);
$counter = explode('_',key($form_data));
?>
<table>
<?php
$i = 1;
$j = 1;
for ($k = 1; $k <= $counter[1]; $k++) {
?>
<tr>
<td><?php echo $form_data['input_' . $j . '_' . $i]; ?></td>
<td><?php $i++;echo $form_data['input_' . $j . '_' . $i]; ?></td>
<td><?php $i++;echo $form_data['input_' . $j . '_' . $i]; ?></td>
</tr>
<?php
if ($i == 3) {
$i = 1;
$j++;
}
}
?>
</table>
Related
This code shows every info from an XML. I want to only display row number one (first from/to, symbol temperature etc)
<?php
$url = ('https://www.yr.no/sted/Norge/oslo/oslo/oslo/varsel_time_for_time.xml');
$feed = simplexml_load_file($url) or die('Can not connect to server');
$result = array();
foreach ($feed->forecast->tabular->time as $content) {
array_push($result, [ "from" => (string)$content['from'],
"to" => (string)$content['to'],
'symbol' => (string)$content->symbol['name'],
'symbol-icon' => (string)$content->symbol['var'],
'temperature' => (string)$content->temperature['value'],
'windDirection' => (string)$content->windDirection['name'],
'windSpeed' => (string)$content->windSpeed['mps'],
'windType' => (string)$content->windSpeed['name'],
]);
}
?>
<button class="collapsible"><div class="tbl-content">
<table cellpadding="0" cellspacing="0" border="0">
<tbody>
<?php foreach ($result as $value) { ?>
<tr>
<td>Oslo</td>
<td><?php echo date("j. M", strtotime($value['from'])); ?> kl.<?php echo date("G", strtotime($value['from'])); ?></td>
<td><img src="http://yr.github.io/weather-symbols/png/100/<?php echo $value['symbol-icon'];?>.png" /></td>
<td><?php echo $value['temperature'] ?> °C</td>
<td><?php echo $value['windType'] ?>, <?php echo $value['windSpeed'] ?> m/s fra <?php echo $value['windDirection'] ?></td>
<td>Longtherm</td>
<td>Hour</td>
</tr>
<?php } ?>
</tbody>
</table>
</div></button>
quite unexperienced, any help is greatly appreciated
Just one of the rows? Remove the foreach! Just use $result[0] in place of $value. :-)
A defined number of rows? Use a for loop:
for ($x = 0; $x < $limit; $x++) {
$value = $result[$x];
// etc
}
My question is:
If you look at where it would display "
<td>1ST<?php echo $first ?></td>
"
How do I ensure that if the row associate to variable '$first' or all the others if they are empty nothing shows. Also that the '1st' doesn't show?
Have tried various things I am stumped on this!
<h2><?php echo $show_title ?></h2>
<h4>Show Date: <span class="glyphicon glyphicon-time"> </span><?php echo $show_date ?></h4>
<hr>
</a>
<hr>
<?php
// SO UPDATE THE QUERY TO ONLY PULL THAT SHOW'S DOGS
$query = "SELECT * FROM result
WHERE first IS NOT NULL";
$result = mysqli_query($connection, $query) or trigger_error
("Query Failed! SQL: $query - Error: ". mysqli_error
($connection), E_USER_ERROR);
if ($result) {
while ($row = mysqli_fetch_assoc($result)) {
$dog_name = $row['dog_name'];
$placement = $row['placement'];
$class_name = $row['class_name'];
$entries = $row['entries'];
$absentee = $row['absentee'];
$entries = $row['entries'];
$first = $row['first'];
$second = $row['second'];
$third = $row['third'];
$RES = $row['RES'];
$VHC = $row['VHC'];
$DCC = $row['DCC'];
$RDCC = $row['RDCC'];
$BCC = $row['BCC'];
$RBCC = $row['RBCC'];
$BOB = $row['BOB'];
$BP = $row['BP'];
$BJ = $row['BJ'];
?>
<table class="table" border="0"></div>
<tr>
<td><strong><?php echo $class_name ?></strong> - <h6>Entries: <?php echo $entries ?> Absentees: <?php echo $absentee ?></h6></td>
<td></td>
</tr>
<tr>
<td>DCC</td>
<td><?php echo $DCC ?></td>
</tr>
<tr>
<td>RDCC</td>
<td><?php echo $RDCC ?></td>
</tr>
<tr>
<td>BCC</td>
<td><?php echo $BCC ?></td>
</tr>
<tr>
<td>RBCC</td>
<td><?php echo $RBCC ?></td>
</tr>
<tr>
<td>BOB</td>
<td><?php echo $BOB ?></td>
</tr>
<tr>
<td>BP</td>
<td><?php echo $BP ?></td>
</tr>
<tr>
<td>BJ</td>
<td><?php echo $BJ ?></td>
</tr>
<tr>
<td>1ST</td>
<td><?php echo $first ?></td>
</tr>
<tr>
<td>2ND</td>
<td><?php echo $second ?></td>
</tr>
<tr>
<td>3RD</td>
<td><?php echo $third ?></td>
</tr>
<tr>
<td>RES</td>
<td><?php echo $RES ?></td>
</tr>
<tr>
<td>VHC</td>
<td><?php echo $VHC ?></td>
</tr>
</table>
You're doing well, just apply a filtering function to each row you recieve:
// SO UPDATE THE QUERY TO ONLY PULL THAT SHOW'S DOGS
$query = "SELECT * FROM result
WHERE first IS NOT NULL";
$result = mysqli_query($connection, $query);
if (!$result) {
trigger_error("Query Failed! SQL: $query - Error: ". mysqli_error($connection), E_USER_ERROR);
} else {
// Fetch results into array
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
// If results array is not empty
if ($data) {
echo '<table class="table" border="0"></div>
<tr>
<td>
<strong><?php echo $class_name ?></strong> - <h6>Entries: <?php echo $entries ?> Absentees: <?php echo $absentee ?></h6>
</td>
<td></td>
</tr>';
// Now let's walk through every record
array_walk($data, function($dogRecord) {
// Here we apply array_filter to each dog record, so that empty values (i.e. those evaluating to false) are filtered out
$dogRecord = array_filter($dogRecord);
// Now loop throw $dogRecord to build table
$collation = [
'DCC' => 'DCC',
'RDCC' => 'RDCC',
'BCC' => 'BCC',
'RBCC' => 'RBCC',
'BOB' => 'BOB',
'BP' => 'BOB',
'BJ' => 'BOB',
'1ST' => 'first',
'2ND' => 'second',
'3RD' => 'third',
'RES' => 'RES',
'VHC' => 'RES'
];
foreach ($dogRecord as $property => $value) {
echo '<tr>
<td>'.$collation[$property].'</td>
<td>'.$value.'</td>
</tr>';
}
});
echo '</table>';
}
}
Note that instead of simple foreach loop I'm using array_walk function. This is because since you extract variables for each record, you want undeclared (i.e. unoccupied) varables every time.
What about this:
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
// Show the table-row
}
}
The following code will iterate through each row in the result (while loop) and each key => value within each row (foreach loop); it will then check if a value is not null or the key is not equal to 'first' (if statement) and echo the results in the table element. I'm not sure I fully understood your question but I hope this helps in some small way.
<table>
<?php
if($result){
while($row = mysqli_fetch_assoc($result))
foreach($row as $key => $value){
if($value != null && $key != 'first'){
echo '<tr>';
echo '<td>' . $key . '</td>';
echo '<td>' . $value . '</td>';
echo '</tr>';
}
}
}
?>
</table>
I have an array $day and want to display this array in table form (I'm working with CI)
Array (
[START_EXECUTION] =>
Array (
[0] => 27-OCT-14
[1] => 28-OCT-14
[2] => 29-OCT-14
)
[NUM_OF_POPULATION] =>
Array (
[0] => 6171
[1] => 6990
[2] => 6882
)
[SUM_AMOUNT] =>
Array (
[0] => 361154716.01
[1] => 409210099.77
[2] => 407191552.71
)
)
Here is my code that I use in view :
<?php
if(count($day)>0){
print_r($day);
foreach($day as $index => $dt1_element){
?>
<table class='table'>
<tr>
<td><?= $index ?></td>
</tr>
<?php
foreach($dt1_element as $row){
?>
</tr>
<td><?= $row ?></td>
<?php
}
?>
</tr>
<?php
}
?>
</table>
<?php
}
?
But what I get is like this :
START_EXECUTION
27-OCT-14
28-OCT-14
29-OCT-14
NUM_OF_POPULATION
6171
6990
6882
SUM_AMOUNT
361154716.01
409210099.77
407191552.71
The result should be :
START_EXECUTION NUM_OF_POPULATION SUM_AMOUNT
27-OCT-14 6171 361154716.01
28-OCT-14 6990 409210099.77
29-OCT-14 6882 407191552.71
Kindly show me the correct foreach to get the desired result. Thank you
Try this:
echo '<table>';
$cols = array_keys($day);
echo '<tr>';
foreach ($cols as $col) echo '<th>' . $col . '</th>';
echo '</tr>';
foreach ($day[$cols[0]] as $i => $null) {
echo '<tr>';
foreach ($cols as $col) echo '<td>' . $day[$col][$i] . '</td>';
echo '</tr>';
}
echo '</table>';
demo
You are unnecessarily closing <tr>.
All you need is the child amounts on a separate row.
Corrected code:
<?php
if(count($day)>0){
print_r($day);
foreach($day as $index => $dt1_element){
?>
<table class='table'>
<tr>
<td><?php echo $index;?></td>
</tr>
<?php
$tds = array();
foreach($dt1_element as $row){
$tds[] = '<td>'.$row.'</td>';
?>
<?php
}
echo "<tr>". impldoe(' ', $tds) ."</tr>";
?>
<?php
}
?>
</table>
<?php
}
?>
if you use PHP>=5.5 than
echo "<table>";
$cols = array_keys($day);
echo "<tr><th>";
echo implode('</th><th>', $cols);
echo "</th></tr>";
for ($i = 0, $num = count($cols); $i < $num; ++$i)
{
echo "<tr><td>";
echo implode('</td><td>', array_column($day, $i));
echo "</td></tr>";
}
echo "</table>";
Here works fine
print "<table><tr><th>START_EXECUTION |</th><th>NUM_OF_POPULATION |</th><th>SUM_AMOUNT |</th></tr>";
//$index=0;
foreach($vals['START_EXECUTION'] as $index=>$values){
echo "<tr><td>$values</td><td>".$vals['NUM_OF_POPULATION'][$index]."</td><td>".$vals['SUM_AMOUNT'][$index]."</td></tr>";
//$index++;
} print '</table>';
for demo here
My response is inspired by the "Two-Step View" pattern where I build the logical data for the view to avoid any unnecessary information being in the view (for example, I'm not a fan of having array indices in views if I can help it):
<?php
$arr = array(
'START_EXECUTION'=>array(
'27-OCT-14',
'28-OCT-14',
'29-OCT-14',
),
'NUM_OF_POPULATION'=>array(
6171,
6990,
6882,
),
'SUM_AMOUNT'=>array(
361154716.01,
409210099.77,
407191552.71,
),
);
$headers = array_keys($arr);
$body = array_map(function($a, $b, $c) { return array($a, $b, $c); },
$arr['START_EXECUTION'],
$arr['NUM_OF_POPULATION'],
$arr['SUM_AMOUNT']
);
$table = array(
'headers'=>$headers,
'body'=>$body,
);
?>
$table will contain the logical structure of the table in a view independent way.
We can create a simple widget that will convert the logical data into a html table like so:
<table class="table">
<thead>
<tr>
<?php foreach($table['headers'] as $header): ?>
<th><?php echo $header; ?></th>
<?php endforeach; ?>
</tr>
</thead>
<tbody>
<?php foreach ($table['body'] as $row): ?>
<tr>
<?php foreach ($row as $col): ?>
<td><?php echo $col; ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</tbody>
</table>
As long as you maintain the same logical structure, the html code snippet can be placed inside a "widget" and that's the beginning of a table renderer.
Note This is just meant as a prototype and is not intended to be a comprehensive solution.
$data = array($FIELDS);//field value like name,email,password etc.
foreach($data as $row)
{
echo "<tr>";
foreach($row as $column){
echo "<th>".$column."</th>";
}
echo "</tr>";
}
you can create array of field and add field data in array try this ...
I do have associative array in php (id,orderType,details) as in specified sequence.
I want to display this details in html table at runtime [while page loading]
How to achieve this? I have never done anything like this before,so please guide me. Thanks!
echo '<table>';
foreach($yourarray as $row){
echo '<tr>';
foreach($row as $key=>$cell){
echo '<td>'.$cell.'</td>';
}
echo '</tr>';
}
echo '</table>':
//detail() is your assosicative array
echo '<table><tr>';
echo '<td>id</td><td>orderType</td><td>details</td>';
echo '</tr>';
foreach($detail as $row){
echo '<tr>';
echo '<td>'.$row['id'].'</td>';
echo '<td>'.$row['orderType'].'</td>';
echo '<td>'.$row['details'].'</td>';
echo '</tr>';
}
echo '</table>';
<table>
<tr>
<td>Id</td>
<td>Order</td>
<td>Type</td>
<td>Details</td>
</tr>
<?php
$your_array = array( array('id' => 12, 'order'=>1233, 'type'=> 1233, 'details'=>2444),
array('id' => 1, 'order'=>14, 'type'=> 444, 'details'=>88));
foreach($your_array as $row){ ?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['order']; ?></td>
<td><?php echo $row['type']; ?></td>
<td><?php echo $row['details']; ?></td>
</tr>
<?php } ?>
</table>
$headerFlag = false;
$result = "<table border='2'>";
foreach ($array as $row){
$result = $result."<tr>";
if($headerFlag == false){
foreach($row as $key => $cell){
$result = $result."<th>".$key."</th>";
}
$headerFlag = true;
$result = $result."</tr>";
}
foreach($row as $key => $cell){
$result = $result."<td>".$cell."</td>";
}
$result = $result."</tr>";
}
echo $result = $result."</table>";
How do it turn a multidimensional array like:
$fruits['apples']['blue'] = 24;
$fruits['bananas']['blue'] = 12;
$fruits['apple']['red'] = 34;
$fruits['gooseberries']['orange'] = 4;
$fruits['oranges']['red'] = 12;
into a cross referenced table like:
alt text http://1updesign.org/uploads/p24.png
$cols = array('blue', 'red', 'orange');
echo '<table>';
echo '<thead><tr><td></td><th scope="col">' . implode('</th><th scope="col">', $cols) . '</th></tr></thead>';
echo '<tbody>';
foreach($fruits as $label => $row)
{
echo '<tr>';
echo '<th scope="row">' . $label . '</th>';
foreach($cols as $k)
{
echo '<td>' . (isset($row[$k]) ? $row[$k] : 0) . '</td>';
}
echo '</tr>';
}
echo '</tbody>';
echo '</table>';
You’ll want some HTML escaping and such, but that’s the gist of it.
Your array is bad designed. How should one know, that apples is the same as apple. Your array should be constructed this way:
$fruits['apples']['blue'] = 24;
$fruits['apples']['read'] = 24;
$fruits['bananas']['blue'] = 12;
$fruits['gooseberries']['orange'] = 4;
$fruits['oranges']['red'] = 12;
Then iterating is easy. The first level of the array are the rows. So:
<?php
$column_head = array();
foreach($fruits as $key => $value) {
$column_head = array_merge($column_head, array_keys($value));
}
$column_head = array_unique($column_head);
print_r($column_head);
?>
<table>
<tr>
<th></th>
<?php foreach($column_head as $head): ?>
<th><?php echo $head; ?></th>
<?php endforeach; ?>
</tr>
<?php foreach($fruits as $fruit => $amount): ?>
<tr>
<td><?php echo $fruit ?></td>
<?php foreach($column_head as $head): ?>
<td><?php echo isset($amount[$head]) ? $amount[$head] : 0 ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</table>
This generates which columns to use on fly, but it can be hardcoded which might be easier. As the code uses a lot loops it might be not that efficient...