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...
Related
My problem is that my code always starts at the first position. So I can't give each line it's input field with the relating id.
foreach ($phase as $line) {
echo "<tr>";
echo "<td>";
echo "<div class='headliner-th'><b>".$line['title']."</b></div>";
echo "</td>";?>
<?php foreach($items as $i=>$item): ?>
<td><?= $form->field($item,"[$i]content")->textInput(['maxlength' => 200])->label(false); ?></td>
<?php endforeach; ?>
<?php echo "</tr>";
}
So how can I avoid to get the same input field again when it comes to a new row?
The inner foreach loop always loops over the same variable $items. Shouldn't it be something that is somehow cycled through by the outer foreach?
I did it with multiple if cases. It seems a bit dirty but easier than harass my object. So it looks like this: I hope anybody can use it: It is important to pre sort the object firstly on row than on col
<table class="sal-list" style="width: 100%;">
<tr>
<?php
$width = 100/(count($pos)+1);
echo "<th style='width:".$width."%;'></th>";
foreach ($pos as $item) {
echo "<th style='width:".$width."%;'><div class='headliner-th'>".$item['title']."</div></th>";
}
?>
</tr>
<?php
$g = 0;
foreach ($phase as $line) {
echo "<tr>";
echo "<td>";
echo "<div class='headliner-th'><b>".$line['title']."</b></div>";
echo "</td>";?>
<?php foreach($items as $i=>$item): ?>
<?php if (($g <= count($items)) and ($g == $i) and ($line['id'] == $item['phas_id'])) : ?>
<td><?= $form->field($item,"[$i]content")->textInput(['maxlength' => 200])->label(false); ?></td>
<?php $g++; endif;?>
<?php endforeach; ?>
<?php
echo "</tr>";
}
?>
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 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>
I am using php and have the following structure
<?php if(!empty($bids)): ?>
<?php foreach ($bids as $bid):?>
<tr>
<td><?php if($bid['Bid']['debit'] > 0) : ?><?php echo $bid['Bid']['debit']; ?><?php else: ?> <?php endif; ?></td>
<td><?php if($bid['Bid']['credit'] > 0) : ?><?php echo $bid['Bid']['credit']; ?><?php else: ?> <?php endif; ?></td>
</tr>
<?php endforeach; ?>
<?php endif;?>
Now i need to calculate the sum total in each case. I know its easy but not getting how to use loop within the foreach to calculate the total value. Please suggest how to do that loop.
If suppose for the first td sample output structrue is as like below, i need to add up all and just display 22 and not the array
0 2 0 20
Try with:
<?php
if(!empty($bids)) {
$debitSum = 0;
$creditSum = 0;
foreach ($bids as $bid) {
$debit = $bid['Bid']['debit'];
$credit = $bid['Bid']['credit'];
echo '<tr>';
echo '<td>' . ( $debit > 0 ? $debit : ' ' ) . '</td>';
echo '<td>' . ( $credit> 0 ? $credit : ' ' ) . '</td>';
echo '</tr>';
$debitSum += $debit;
$creditSum += $credit;
}
echo '<tr style="font-weight: bold">';
echo '<td>' . $debitSum . '</td>';
echo '<td>' . $creditSum . '</td>';
echo '</tr>';
}
?>
Edit:
If $bid['Bid']['debit'] (or credit too) is a string value, then cast it to int value:
$debit = (int) $bid['Bid']['debit'];
Why don't you add a counter variable outside the foreach?
<?php
$total['debit'] = 0;
$total['credit'] = 0;
foreach ((array)$bids as $bid)
{
$debit = ($bid['Bid']['debit'] > 0)? $bid['Bid']['debit'] : 0;
$credit = ($bid['Bid']['credit'] > 0)? $bid['Bid']['credit'] : 0;
$total['debit'] += $debit;
$total['credit'] += $credit;
$output =<<<XHTML
<tr>
<td>{$debit}</td>
<td>{$credit}</td>
</tr>
XHTML;
echo $output;
}
?>
It's better to define variable inside the loop and add values to the variable and then print the variable.
I am trying to make a table with 4 rows from a foreach-call.
My problem is, that in the result I get each ID twenty times in the same column.
I'm using this code:
<table width="80%" border="0" cellpadding="10px">
<?php foreach (array_chunk($items, 4) as $row) { ?>
<?php
$i = 0;
foreach ($items as $item):
$class = null;
if ($i++ % 2 == 0) {
$class = ' class="altrow"';
} ?>
<tr
<?php echo $class;?>
>
<?php foreach ($row as $item){ ?>
<td>
<?php echo htmlentities ($item['Item']['id']); ?>
</td>
<?php } ?>
<?php endforeach; ?>
</tr>
<?php } ?>
</table>
Any idea how I could get each ID just once?
You are incrememnting $i at every $item as opposed to every $row
Is this the fix you are looking for?
Edit: Mikel has your fix, add this to fix the row bug (Typical of me to notice that first eck!)
<table width="80%" border="0" cellpadding="10px">
<?php
$i = 0;
$chunkedarray = array_chunk($items, 4);
foreach ($chunkedarray as $row) {
$class = null;
if ($i++ % 2 == 0)
$class = ' class="altrow"';
echo "<tr ".$class.">";
foreach ($row as $item){
echo "<td>";
echo htmlentities ($item['Item']['id']);
echo "</td>";
}
echo "</tr>";
}?>
</table>