How to correctly print the repeated rows? - php

I have simulated the mysql result from an old SO question as the following array:
<?php
$arr = array(
array(
'title'=>'Test',
'name'=>'ABC',
'cat_desc'=>'ABC_DESC',
'parent'=>0,
'parent_menu'=>1
),
array(
'title'=>'Test2',
'name'=>'DEF',
'cat_desc'=>'DEF_DESC',
'parent'=>0,
'parent_menu'=>2
),
array(
'title'=>'Test2',
'name'=>'GHI',
'cat_desc'=>'GHI_DESC',
'parent'=>1,
'parent_menu'=>0
),
array(
'title'=>null,
'name'=>'JKL',
'cat_desc'=>'JKL_DESC',
'parent'=>2,
'parent_menu'=>0
)
);
//print_r($arr);
?>
Now I wonder if I could print the result in this format:
<table>
<tr>
<th>Name</th>
<th>Description</th>
</tr>
<tr>
<td> Menu Title Test </td>
<td> Main Category ABC</td>
</tr>
<tr>
<td>GHI</td>
<td>GHI_DESC</td>
</tr>
<tr>
<td> Menu Title Test2 </td>
<td> Main Category DEF</td>
</tr>
<tr>
<td>JKL</td>
<td>JKL_DESC</td>
</tr>
</table>
I am trying the following php to print but it could not give the expected result:
<table>
<tr>
<th>Name</th>
<th>Description</th>
</tr>
<?php
$r = 0;
while(list($key, $val)=each($arr)) {
if($val['parent']==0):
if($r % 1==0): ?>
<tr>
<td> Menu Title <?php echo $val['title'];?> </td>
<td> Main Category <?php echo $val['name'];?></td>
</tr>
<?php endif;
endif;
if($val['parent']!=0){ ?>
<tr>
<td><?php echo $val['name'];?></td>
<td><?php echo $val['cat_desc'];?></td>
</tr>
<?php
}
$r++;
} ?>
</table>
Your help and suggestion is very much welcome.

I find it difficult to figure out what you exactly want from your array structure. But I noticed that array element 0 is paired with element 2, and element 1 is paired with element 3. Therefore my code would be like following. It will give you exactly the table that you wanted.
print "<table border=1>";
$numArray = count($arr) / 2;
for($i=0;$i<$numArray;$i++) {
$element = $arr[$i];
print "<tr><td>Menu Title {$element['title']}</td><td>Main Category {$element['name']}</td></tr>";
$element = $arr[$i+2];
print "<tr><td>{$element['name']}</td><td>{$element['cat_desc']} </td></tr>";
}
print "</table>";

You can use this where I commented what to do and why
<table>
<tr>
<th>Name</th>
<th>Description</th>
</tr>
<?php
// Store the array into temporary array
$temp_array = $arr;
foreach ($arr as $akey => $sArr)
{
// Check that prrent is 0
if ( $sArr['parent'] ==0 )
{
// Store parent_menu id
$parent_menu = $sArr['parent_menu'];
?>
<tr>
<td> Menu Title <?php echo $sArr['title'];?> </td>
<td> Main Category <?php echo $sArr['name'];?></td>
</tr>
<?php
// Unset or remove current index from array
unset($temp_array[$akey]);
// Iterate all rows
foreach ($temp_array as $skey => $aval)
{
// Check that it has parent for the current menu
if ( $aval['parent'] == $parent_menu )
{
?>
<tr>
<td><?php echo $aval['name'];?></td>
<td><?php echo $aval['cat_desc'];?></td>
</tr>
<?php
}
}
// End of foreach
}
// End of if
}
// End of foreach
?>
</table>

I find that data from a relational DB doesn't really lend itself to direct use and requires some massaging to lower the code complexity. So, if your aim is to make a dynamic menu with submenus, I would suggest refactoring the data structure into more of a tree structure and then looping over each level.
A better data structure would be:
$menus = array(
1 => array( // original array item index 0
'title'=>'Test',
'name'=>'ABC',
'cat_desc'=>'ABC_DESC',
'parent'=>0,
'parent_menu'=>1
'children'=> array( // new array containing submenus
array( // original array item index 2
'title'=>'Test2',
'name'=>'GHI',
'cat_desc'=>'GHI_DESC',
'parent'=>1,
'parent_menu'=>0
),
),
),
2 => array( // original array item index 1
'title'=>'Test2',
'name'=>'DEF',
'cat_desc'=>'DEF_DESC',
'parent'=>0,
'parent_menu'=>2
'children'=> array( // array containing original item index 2
array(
'title'=>null,
'name'=>'JKL',
'cat_desc'=>'JKL_DESC',
'parent'=>2,
'parent_menu'=>0
),
),
),
);
Rather than just entering the data in this more covenient form, it is good practice to convert it. So, to get from the original data to this structure you can use a simple single pass foreach loop:
$menus = [];
foreach($arr as $item) {
if($item['parent'] == 0) {
$item['children'] = array();
$menus[$item['parent_menu']] = $item;
}
else {
$menus[$item['parent']]['children'][] = $item;
}
}
Once you have the data in a nice convenient form you can use simple nested foreach loops to iterate it and output the table in a clear manner like this:
<table>
<tr>
<th>Name</th>
<th>Description</th>
</tr>
<?php foreach($menus as $menu) { ?>
<tr>
<td> Menu Title <?php echo $menu['title'];?> </td>
<td> Main Category <?php echo $menu['name'];?></td>
</tr>
<?php foreach($menu['children'] as $child) { ?>
<tr>
<td><?php echo $child['name'];?></td>
<td><?php echo $child['cat_desc'];?></td>
</tr>
<?php } } ?>
</table>

From what I see, I believe $r % 2 makes a little more sense than $r % 1
In case $r is an integer, $r % 1 will always return a zero. Looks like in your case you use this to split logic for odd and even numbers, which makes sense for your data set.
Make sure the data set doesn't change. Maybe it'd be better use a more reliable approach. Adding indexes to the data set wouldn't harm either :)

Related

sort specific array element value

I have the following array...
Array
(
[banana] => 1
[orange] => 2
[mango] => 1
)
What I need is How do i get the exact string value to view on the following table. example the banana value to the add to 1. banana table column value.
The table below is HTML View table, Not Mysql table.
type value
-------------------
1.mango |
2.banana |
3.orange |
------------------
in short how do i search the array to get the value of each and insert value to table below.
You simply need to use a foreach.
<?php
$array = array("banana" => 1, "orange" => 2, "mango" => 1);
?>
<table>
<tr>
<th>Type</th>
<th>Value</th>
</tr>
<?php
foreach($array as $key => $val){
?>
<tr>
<td><?php echo $val; ?></td>
<td><?php echo $key; ?></td>
</tr>
<?php
}
?>
</table>
Output :
The same format as your question would be :
<?php
$array = array("banana" => 1, "orange" => 2, "mango" => 1);
?>
<table>
<tr>
<th>Type</th>
<th>Value</th>
</tr>
<?php
$i = 0;
foreach($array as $key => $val){
$i++;
?>
<tr>
<td><?php echo "$i.$key"; ?></td>
<td></td>
</tr>
<?php
}
?>
</table>
Output :
Internet,
combine foreach and switch.
http://php.net/manual/en/control-structures.foreach.php
http://php.net/manual/en/control-structures.switch.php
Use a foreach to loop through your array and then insert this in your database.
foreach( $fruits as $fruit -> $value{
...passing data to your database insert function
...i.e. $result = mysql_query("INSERT INTO kunden (type, value) VALUES ('".$fruit."', '".$value."')");
}

multiply 2 values from different table using codeigniter and postgresql foreach()

Here's the code from my
Controller Page
public function table1(){
$this->load->model('test_model');
$data['value']= $this->test_model->getAlltable1();
$data['value2']= $this->test_model->getAlltable0();
$this->load->view('table1', $data);
}
Views Page
<table class="table">
<tbody>
<?php foreach ($value as $v){ ?>
<?php foreach ($value2 as $v2){ ?> //different table
<tr>
<td><?php echo $v->tech_voc?></td>
<td><?php echo ($v->tech_voc*$v2->tech_voc)?></td>
</tr>
<?php } ?>
<?php } ?>
The output is somewhat like this
1 .75
1 .75
1 .75
1 .75
What I want to display is something like this
1 .75
What happen here is that, instead it multiply once, it all multiply each row. And I think it is because I put foreach inside a foreach Please help me.
EDIT
Oh yeah, I already tried deleting the foreach value2
but it says v2 is undefined variable
HOPE it helps.
NEW EDIT:---------------------------------------
If you're trying to multiply where the keys are the same ($value[0]*$value2[0], $value[1]*$value2[1], etc) try this.
<?php
$col1_sum = 0;
$col2_sum = 0;
foreach ($value as $k => $v){ ?>
<tr>
<td><?php echo $v->tech_voc?></td>
<td><?php echo ($v->tech_voc*$value2[$k]->tech_voc)?></td>
<?php //update sums
$col1_sum += $v->tech_voc;
$col2_sum += ($v->tech_voc*$value2[$k]->tech_voc);
?>
</tr>
<?php } ?>
<!-- row with sums -->
<tr>
<td><?php echo $col1_sum?></td>
<td><?php echo $col2_sum?></td>
</tr>
Edited based on comments/chat to include a sum row.

php get the same index values from two arrays (outside foreach)

Have array named for example $data_debit_turnover
Array
(
[0] => Array
(
[VatReturnRowNumberForDebitTurnover] => 63
[Total] => 0.00
)
[1] => Array
(
[VatReturnRowNumberForDebitTurnover] => 64
[Total] => 44.28
)
)
Have HTML that need to look like this
<table><tr>
<td><strong>63</strong></td>
<td>0.00</td>
</tr><tr>
<td><strong>64</strong></td>
<td>44.28</td>
</tr></table>
At first tried with php foreach, but in such case instead of one table get multiple tables [0], [1] etc.
Then tried
<td><strong>64</strong></td>
<td><?php
if( $data_debit_turnover[1][VatReturnRowNumberForDebitTurnover] == '64'){
echo $data_debit_turnover[1][Total]. ' Total<br>';
}?>
</td>
but problem is with [1] etc. I do not know number of []; may be [1] and may be [30].
Tried something like this
$resultVatReturnRowNumberForDebitTurnover = array();
$resultTotal = array();
foreach($data_debit_turnover as $i => $result){
$resultVatReturnRowNumberForDebitTurnover[] = $result[VatReturnRowNumberForDebitTurnover];
$resultTotal[] = $result[Total];
}
<td><strong>64</strong></td>
<td><?php
if (in_array('64', $resultVatReturnRowNumberForDebitTurnover)) {
echo $resultTotal[1];
}?>
</td>
The same problem [1]. How to echo corresponding (index) value from the another array.
For example if 64 is the second value in array $resultVatReturnRowNumberForDebitTurnover then need to echo the second value from array $resultTotal.
Possibly there is some other way.
Please advice.
Showing what I did with foreach
<?php
foreach($data_debit_turnover as $i => $result){
?>
<table>
<tr>
<td><strong>63</strong></td>
<td>
<?php if($result[VatReturnRowNumberForDebitTurnover] = '63') {
echo $result[Total];
} ?>
</td>
</tr>
<tr>
<td><strong>64</strong></td>
<td>
<?php if($result[VatReturnRowNumberForDebitTurnover] = '64') {
echo $result[Total];
} ?>
</td>
</tr>
</table>
<?php
}
?>
Update Thanks to #user2340218 advice get some solution. For each <td> must use foreach. Possibly there is some better solution.
<table><tr>
<td><strong>64</strong></td>
<td><?php foreach($data_debit_turnover as $vatReturn){if($vatReturn['VatReturnRowNumberForDebitTurnover'] == '64') {echo $vatReturn['Total'];}}?></td>
</tr><tr>
<td><strong>67</strong></td>
<td><?php foreach($data_debit_turnover as $vatReturn){if($vatReturn['VatReturnRowNumberForDebitTurnover'] == '67') {echo $vatReturn['Total'];}}?></td>
</tr></table>
Solution Finally used solution #Daniel P advised.
$resultVatReturnRowNumberForDebitTurnover = array();
$resultTotal = array();
foreach($data_debit_turnover as $i => $result){
$resultVatReturnRowNumberForDebitTurnover[] = $result[VatReturnRowNumberForDebitTurnover];
$resultTotal[] = $result[Total];
}
$VatReturnRowNumberForDebitTurnoverModified = array_combine($resultVatReturnRowNumberForDebitTurnover, $resultTotal);
<table>
<tr>
<td><strong>62</strong></td>
<td>
<?php echo $VatReturnRowNumberForDebitTurnoverModified[62]; ?>
</td>
</tr>
<tr>
<td><strong>63</strong></td>
<td>
<?php echo $VatReturnRowNumberForDebitTurnoverModified[63]; ?>
</td>
</tr>
</table>
Actually have to accept #Daniel P answer:) But as understand can not accept 2 answers
I am guessing that VatReturnRowNumberForDebitTurnover numbers are unique so your array should look like this :
Array
(
[63] => 0.00
[64] => 44.28
)
The array index is your VatReturnRowNumberForDebitTurnover and the value is your total.
To test if a VatReturnRowNumberForDebitTurnover has a value your simply use isset()
if (isset($array[63])) {
echo $array[63]
}
Building the table :
<table>
<?php foreach($data_debit_turnover as $i => $total){ ?>
<tr>
<td><strong><?php echo $i; ?></strong></td>
<td><?php echo $total; ?></td>
</tr>
<?php } ?>
</table>
Do you mean this?
<table>
<?php foreach($data_debit_turnover as $vatReturn){ ?>
<tr>
<td><strong><?php print $vatReturn['VatReturnRowNumberForDebitTurnover'] ?></strong></td>
<td><?php print $vatReturn['total'] ?></td>
</tr>
<?php } ?>
</table>
Use foreach like this:
<table>
<?php
foreach ($Array as $item)
{
echo '<tr>';
echo '<td><strong>' . $item['VatReturnRowNumberForDebitTurnover'] . '</strong></td>';
echo '<td>' . $item['Total'] . '</td>';
echo '</tr>'
}
?>
</table>

create a new array based on a function

I'm just learing to use php, and I've been working on this code that is not very efficient because it is very long and I would like it to be more automated. The idea is to generate a table with 2 colums, one with the user name and the other with the score of each user. As you may imagine, the score is based on a function that use other variables of the same user. My goal is to only have to set one variable for each user and a new row is would be created automatically at the end of the table.
<?php
$array1['AAA'] = "aaa"; ## I'm suposed to only set the values for array1, the rest
$array1['BBB'] = "bbb"; ## should be automatic
$array1['ETC'] = "etc";
function getscore($array1){
## some code
return $score;
};
$score['AAA'] = getscore($array1['AAA']);
$score['BBB'] = getscore($array1['BBB']);
$score['ETC'] = getscore($array1['ETC']);
?>
<-- Here comes the HTML table --->
<html>
<body>
<table>
<thead>
<tr>
<th>User</th>
<th>Score</th>
</tr>
</thead>
<tbody>
<tr>
<td>AAA</td> <-- user name should be set automaticlly too -->
<td><?php echo $score['AAA'] ?></td>
</tr>
<tr>
<td>BBB</td>
<td><?php echo $score['BBB'] ?></td>
</tr>
<tr>
<td>ETC</td>
<td><?php echo $winrate['ETC'] ?></td>
</tr>
</tbody>
</table>
</body>
</html>
Any help would be welcome!
$outputHtml = ''
foreach( $array1 as $key => $val )
{
$outputHtml .= "<tr> ";
$outputHtml .= " <td>$key</td>";
$outputHtml .= " <td>".getscore($array1[$key]);."</td>";
$outputHtml .= " </tr>";
}
then in $outputHtml will be html content with all rows you wanna display
This is a little cleaner, using foreach and printf:
<?php
$array1 = array(
['AAA'] => "aaa",
['BBB'] => "bbb",
['ETC'] => "etc"
);
function getscore($foo) {
## some code
$score = rand(1,100); // for example
return $score;
};
foreach ($array1 as $key => $value) {
$score[$key] = getscore($array1[$key]);
}
$fmt='<tr>
<td>%s</td>
<td>%s</td>
</tr>';
?>
<-- Here comes the HTML table --->
<html>
<body>
<table><thead>
<tr>
<th>User</th>
<th>Score</th>
</tr></thead><tbody><?php
foreach ($array1 as $key => $value) {
printf($fmt, $key, $score[$key]);
}
?>
</tbody></table>
</body>
</html>
Also, I'll just note that you don't seem to be using the values of $array1 anywhere. Also,
I'm not sure what $winrate is in your code, so I ignored it.

How to sum up values inside a array variable?

I have retrieved some values from database. In my view file I have the following:
$row['fee_amount'];
Now, I want to sum up all the values inside $row['fee_amount']; and then show it.
I know I could sum up when querying the database, but I am interested to learn how to add using PHP .
Would you please kindly teach me how to do it?
EDIT
<?php if(count($records) > 0) { ?>
<table id="table1" class="gtable sortable">
<thead>
<tr>
<th>S.N</th>
<th>Fee Type</th>
<th>Fee Amount</th>
</tr>
</thead>
<tbody>
<?php $i = 0; foreach ($records as $row){ $i++; ?>
<tr>
<td><?php echo $i; ?>.</td>
<td><?php echo $row['fee_type'];?></td>
<td><?php echo $row['fee_amount'];?></td>
</tr>
<?php } ?>
</tbody>
<tr>
<td></td>
<td>Total</td>
<td>
I WANT TO DISPLAY THE SUMMATION RESULT HERE ADDING UP VALUES INSIDE THIS>>> <? $row['fee_amount']; ?>
</td>
</tr>
</table>
<?php } ?>
In your view file, with your foreach loop, add a $sum variable next to your $i counter and add the amount per each iteration (similar to like you increase $i):
<?php
$i = 0;
$sum = 0;
foreach ($records as $row)
{
$i++;
$sum += $row['fee_amount']; ?>
(I put this over multiple lines to make it more readable).
After the foreach has finished, $sum contains the total amount:
<td>Total: <?php echo $sum; ?></td>
That simple it is. You only need a new variable ($sum) and do the calculation.
Use a loop
$sum = 0;
while($row...){
$sum += $row['fee_amount']
}
echo $sum;
You could use;
$someValue = 0;
foreach($row["fee_amount"] as $value) {
$someValue = $someValue + $value;
}
using this php function, if $row['fee_amount'] is an array ^_^
for example:
$a = array(2, 4, 6, 8);
array_sum($a)

Categories