sort specific array element value - php

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."')");
}

Related

Move result to the right position on table in PHP

I'm trying to show 7 results on a table (image 1) which I would like to move them to the right position.
Mon = 1 ~ Sun = 7 as we can see on the array and where there is no value I would like to have it $0. At the moment I could not figure out how to move it to the right spot on the table.
Here is my code:
$w_rep = "SELECT
`totals`.`totals_weeknumb`,
`totals`.`totals_weekday`,
`totals`.`totals_of_day`
FROM `totals`
WHERE `totals`.`totals_has_users_id` = :fromID";
$w_rep_stmt = $DB->prepare($w_rep);
$w_rep_stmt->execute(array(':fromID' => $fromID));
$w_rep_stmt->setFetchMode(PDO::FETCH_ASSOC);
$totals_of_day = array();
foreach ($w_rep_stmt as $report) {
//$tdate = new DateTime($report['totals_date']);
//$totals_date = $tdate->format('d-m-Y');
$t_wnumber = (int)$report['totals_weeknumb'];
$t_wday = (int)$report['totals_weekday'];
$totals_of_day[$t_wnumber][$t_wday] = (float)$report['totals_of_day'];
//$sum_of_week[$t_wnumber] = array_sum(array_column($totals_of_day, ''));
} // close foreach
var_dump(array_keys($totals_of_day));
var_dump($totals_of_day);
foreach ($totals_of_day as $w_n => $y) {
?>
<tr>
<th><?php echo $w_n; ?></th>
<td>More Details</td>
<?php
foreach ($y as $w_day => $saved) {
echo '<td>'. $curr.number_format($saved, 2) .'</td>';
} // close foreach
?>
<td><?php //echo $curr.$sum_of_week[]; ?></td>
</tr>
<?php
} // close 1st foreach
I tried so many options :(
Basically you need to iterate the days of the week and use the index in your array
foreach (range(1, 7) as $day) {
echo (isset($y[$day]) ? $y[$day] : '-');
}
Example:
<?php
$totals_of_day = [
7 => [3 => 150.8, 4 => 523.88, 5 => 95.32, 7 => 10.8],
8 => [1 => 13.78, 2 => 107.33, 4 => 8.49, 5 => 125.67],
9 => [1 => 71.3, 2 => 49.68, 6 => 95, 7 => 100.57],
10 => [1 => 18.34, 2 => 44.9, 3 => 55.7, 4 => 15.58]
];
?>
<table border="1" style="border-collapse: collapse;">
<tr>
<th>Week</th>
<th>Items</th>
<th>Mon</th>
<th>Tue</th>
<th>Wed</th>
<th>Thu</th>
<th>Fri</th>
<th>Sat</th>
<th>Sun</th>
<th>Total Savings</th>
</tr>
<?php foreach ($totals_of_day as $w_n => $y) { ?>
<tr>
<th><?php echo $w_n; ?></th>
<td>More Details</td>
<?php foreach (range(1, 7) as $day) {
echo '<td>'. (isset($y[$day]) ? number_format($y[$day], 2) : '-') .'</td>';
} ?>
<td><?php echo number_format(array_sum($y), 2); ?></td>
</tr>
<?php } ?>
</table>

Filtering an array result in a for each loop

I have this code to create my array from file:
<?php
$servers = array();
$handle = #fopen("data/data.txt", "r");
if ($handle) {
while (($buffer = fgets($handle)) !== false) {
$line = explode("|", $buffer);
$servers[] = array(
"name" => $line[0],
"ip" => $line[1],
"type" => $line[2],
);
}
fclose($handle);
}
?>
then i have this code to display the array:
<?php
foreach ($servers as $name => $servers): ?>
<td style="width:340px;"> <?php echo $servers['name']; ?></td>
<td style="width:240px;"><?php echo $servers['ip']; ?></td>
</tr>
<?php endforeach; ?>
this is the array sample:
Array(
[0] => Array
(
[name] => aaa
[ip] => 123
[type] => good
)
[1] => Array
(
[name] => bbb
[ip] => 345
[type] => good
)
)
suppose i need to filter the result with array type is good,
im trying with this code but it only returns the last array:
<?php
foreach ($servers as $name => $servers): ?>
<?php if($servers['type']=="good"){?>
<td style="width:340px;"> <?php echo $servers['name']; ?></td>
<td style="width:240px;"><?php echo $servers['ip']; ?></td>
</tr>
<?php } ?>
<?php endforeach; ?>
The error is in the variable name in foreach loop (use $server instead of $serves as $servers already exists and contains your data)
<?php foreach ($servers a $server): ?>
<?php if($server['type']=="good"){?>
<tr>
<td style="width:340px;"> <?php echo $server['name']; ?></td>
<td style="width:240px;"><?php echo $server['ip']; ?></td>
</tr>
<?php } ?>
<?php endforeach; ?>
Edit 1
Filter the array, then print it
<?php
//Filter the array
$goodValues = array_filter($servers, function($e){
return $e['type'] == "good";
//Use this to be sure
//return strtolower($e['type']) == "good";
});
//Print the values
foreach ($goodValues as $value): ?>
<tr>
<td style="width:340px;"> <?php echo $value['name']; ?></td>
<td style="width:240px;"><?php echo $value['ip']; ?></td>
</tr>
<?php endforeach; ?>
As this is just numaric array and you're not using the key anywhere inside the body of the loop, you don't need to use as $key => $value and only as $value will suffice. Also notice the different variable names.
<?php foreach ($servers as $server): ?>
<?php if($server['type']=="good"){?>
<tr>
<td style="width:340px;"> <?php echo $server['name']; ?></td>
<td style="width:240px;"><?php echo $server['ip']; ?></td>
</tr>
<?php } ?>
<?php endforeach; ?>

How to correctly print the repeated rows?

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 :)

Cakephp only showing one record out of four records in the database

I have looped through my record, when i use print_r(), i will see all my records, but if i try to display it in a table, it will only show one record.
Please how do i solve this?
<?php foreach ($clists as $clist) ;?>
<tr>
<td><?php echo $clist['Course']['id']; ?></td>
<td><?php echo $this->Html->link($clist['Course']['course_name'], array('controller' => 'this', 'action' => 'this')); ?></td>
<td><?php echo $clist['Course']['course_desc']; ?></td>
<td><?php echo $clist['Course']['closing_day']; ?></td>
</tr> <?php //endforeach; ?> <?php unset($clist); ?> –
}
How do you loop through your array?
Here is a great example on how to echo the results in an array:
<?php
//Example array
$colors = array(
"red",
"green",
"blue",
"yellow"
);
foreach ($colors as $value) {
echo "$value <br>";
}
?>
More info here and here
Also, for example;
$result = array(
[0] => 'DB result 1',
[1] => 'DB result 2',
[2] => 'DB result 3'
);
To show these results in a table for example in this case would be:
<table>
<?php foreach($result as $key => $value) { ?>
<tr>
<td><?= $value ?></td>
</tr>
<?php } // End foreach ?>
</table>
Good luck!

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>

Categories