I have view cart session like this
ID NAME DISC QTY
-- ---- ------ ------
1 AAAA D1 2
1 AAAA D5 1
2 BBBB D1 1
1 AAAA D1 1
What I want is, showing a query session with result like this
NAME TOTAL
---- ------
AAAA 4
BBBB 1
How can I do this?
I have a query like this for show cart:
<?php
if(count($_SESSION[data1][ID])>0)
for($i=0;$i<count($_SESSION[data1][ID]);$i++)
{
if($_SESSION[data1][ID][$i]!='')
{ ?>
<td ><?=$_SESSION[data1][ID][$i]?></td>
<td ><?=$_SESSION[data1][NAME][$i]?></td>
<td ><?=$_SESSION[data1][DISC][$i]?></td>
<td ><?=$_SESSION[data1][QTY][$i]?></td>
<?php } } ?>
You can simply loop through the data adding the quantities to an array indexed by the name.
Quick'n'dirty example
<?php
$names = array("AAA", "BBB", "AAA", "BBB");
$qts = array(1, 2, 3, 4);
for ($i=0; $i<count($names); $i++)
{
$res[$names[$i]] += $qts[$i];
}
$k = array_keys($res);
for ($i=0; $i<count($k); $i++)
{
echo $k[$i] . ":" . $res[$k[$i]] . "<br/>";
}
?>
AAA:4
BBB:6
You can create a new array $resultArray and take $_SESSION['data1'] in foreach loop, and check if ID does exists in $resultArray, if yes, append it, other wise create it.
<?php
$resultArray = array();
if(count($_SESSION['data1'])>0){
foreach($_SESSION['data1'] as $data){
if(isset($resultArray[$data['ID']])){
$resultArray[$data['ID']] += $data['QTY'];
} else {
$resultArray[$data['ID']] = $data['QTY'];
}
}
}
print_r($resultArray); //check out result
?>
Related
I have an script for getting a table from a DB which is written in PHP.
I am trying to add name for each column to be in the first row:
A part of the Code is:
$rows = [];
foreach (range(1, 4) as $row) {
$rows[$row] = "";
}
$rows["Name"] = $order->user->aFirstName;
$rows["Last Name"] = $alumn->aLastName;
$rows["Age"] = $alumn->aAge;
$rows["Gender"] = $alumn->aGender;
$string = "";
foreach ($rows as $r) {
$string .= $r . "\t";
}
what I want to get is
1 | Name | Last Name | Age | Gender
2 | John | Des | 45 | Male.
What I get now is the data in 1st row.
1 | John | Des | 45 | Male.
Any suggestion? Thanks
You can create a new first element in $rows using https://www.php.net/manual/de/function.array-unshift.php
$labels = ["Name" => "NameLabel", "Last Name" => "Last NameLabel" ...];
array_unshift($rows, $labels);
So the first element of the $rows array are the labels. Now when the table is generated is will display the labels at the top.
You are loading the arrays incorrectly.
I assume you dont want to get the column names from the meta data available to you, and are happy to add the column names manually, if not let me know
$rows = [];
// add labels
$rows[] = ["Name", "Last Name", "Age", "Gender"];
#$rows[] = [$order->user->aFirstName, $alumn->aLastName, $alumn->aAge, $alumn->aGender];
// I dont have your data, so this is to simulate the above line
$rows[] = ['John', 'Des', 45, 'Male'];
$string = '';
foreach ($rows as $i => $row) {
$n = $i+1;
$string .= "$n\t";
foreach ($row as $col){
$string .= $col . "\t";
}
$string .= '<br>'. PHP_EOL;
}
print_r($string);
RESULTS, as you can see a Tab is not really enough to correctly format the table
1 Name Last Name Age Gender <br>
2 John Des 45 Male <br>
In my database, the table table_log where I get the data from has 3 columns but I only need: (1) id (2) start (3) end. there are multiple logs with the same id and different start and end values. I'm trying to get the start values so I've placed said values in an array storage. Now, what I'm trying to do is place all values in the arrow in a single cell in the table but only the first value [0] appears not unless I make another column. How can I resolve this?
Query:
$logs = mysql_query("SELECT start FROM table_log WHERE id = '". $resultID."'");
$storage = Array();
while ($res = mysql_fetch_array($logs, MYSQL_ASSOC)) {
$storage[] = $res['start'];
}
Loop:
for($i = 0; $i < count($res); ++$i) {
if(count($res) > $i) {
$start_log = " $storage[$i] <br>";
}
}
$data .= "<td>". $start_log ."</td>";
Database:
id | start | end
01 | 10:00 | 11:00
01 | 12:00 | 01:00
01 | 03:00 | 03:30
Needed Output:
id | start | end
01 | 10:00 | 11:00
| 12:00 | 01:00
| 03:00 | 03:30
First of all - use same variable names ($storage & $storeArray & $res)
Secondly - mysql is removed in php7, instead try to make mysqli or PDO;
Do you want outputting only start times or all data???
$logs = mysql_query("SELECT start FROM table_log WHERE id = $resultID");
$storage = Array(); // from PHP5.6 use fetch_all
while ($res = mysql_fetch_assoc($logs)) {
$storage[] = $res['start'];
}
$output = "<div><b>$resultID:</b>". implode (' | ', $storage) ."</div>";
<?php
$logs = mysql_query("SELECT start FROM table_log WHERE id =$resultID");
while ($res = mysql_fetch_array($logs)) {
?>
<table>
<tr>
<th>id</th>
<th>start</th>
<th>end</th>
</tr>
<tr>
<td><?php echo $res['id'];</td>
<td><?php echo $res['start'];</td>
<td><?php echo $res['end'];</td>
</tr>
</table>
<?php
}
?>
got it! this one worked for me :)
$start_log = "";
$j = 1;
while ($res = mysql_fetch_array($logs, MYSQL_ASSOC)) {
$storage[] = $res['start'];
$j++;
}
for($i = 0; $i<=$ctr; $i++) {
$start_log .= " $storage[$i] <br>";
}
I have a task to create a script which will output multiplication table just for specified number. To create regular multiplication table, for example 10x10 we would write something like this:
echo "<table border=\"1\">";
for ($r =0; $r < $rows; $r++){
echo'<tr>';
for ($c = 0; $c < $cols; $c++)
echo '<td>' .$c*$r.'</td>';
echo '</tr>'; // close tr tag here
}
echo"</table>";
But output which i am supposed to receive, for example for digit "3", should look like this:
|1 x 1 = 1|1 x 2 = 2|1 x 3 = 3|
| ------- | ------- | ------- |
|2 x 1 = 2|2 x 2 = 4|2 x 3 = 6|
|3 x 1 = 3|3 x 2 = 6|3 x 3 = 9|
Anyone got an idea how to echo this using php (while and/or for) loops?
It sounds like you want to output the text of the calculation as well as the result, e.g. 1 x 3 = 3. You're missing that from your output.
Also, you need to start your for loops at 1 rather than 0, otherwise you get 0 x 0 = 0 which I assume you don't want. You would compensate for the loss of iterations by using <= instead of < in your condition of the for loop so you still get 3 iterations (in this example).
Try this:
echo '<table border="1">';
for ($r = 1; $r <= $rows; $r++) {
echo '<tr>';
for ($c = 1; $c <= $cols; $c++) {
echo sprintf('<td>%d x %d = %d</td>', $r, $c, $c * $r);
}
echo '</tr>'; // close tr tag here
}
echo '</table>';
Your expected output also seems to suggest that the first row should be a heading. It would seem odd to me to do that, but if that is the case, you'll need to do this instead:
$cellType = ($r === 1) ? 'th' : 'td'; // use <th> for the first row, otherwise <td>
echo sprintf('<%s>%d x %d = %d</%s>', $cellType, $r, $c, $c * $r, $cellType);
Program:
while($i<=$row) {
echo $arr[$i][1].$arr[$i][4]
}
Output
Product Code Qty
KC_DRINK_TASTY_CASE 1
KC_DRINK_TASTY_CASE 1
KC_DRINK_TASTY_CASE 1
KC_DRINK_TASTY_CASE 1
KC_SUNGLASSES_BK 1
KC_SUNGLASSES_BK 1
KC_SUNGLASSES_BE 1
KC_SUNGLASSES_BE 1
KC_SUNGLASSES_OE 1
KC_SUNGLASSES_OE 1
KC_SUNGLASSES_RD 1
KC_SUNGLASSES_RD 1
KC_SUNGLASSES_WE 1
KC_SUNGLASSES_WE 1
I want it to output
KC_DRINK_TASTY_CASE 4
KC_SUNGLASSES 10
so that it group product code excluding last underscore and sum their quantity
If $arr looks something like this:
$arr = array(
array('{something}', 'KC_DRINK_TASTY_CASE', '{something}', '{something}', 1),
array('{something}', 'KC_SUNGLASSES_BK', '{something}', '{something}', 1),
// ...
);
Then you can get the output what you what like this:
// we'll store counts here
$result = array();
foreach ($arr as $row) {
$product = $row[1];
$qty = $row[4];
// figure out where the last underscore is and chop off everything that follows it
// this is VERY brittle. If the product ends up with a name like _SOMEKEY you'll end
// up with an empty key. Not good. Probably not a huge issue, but buyer beware
$_product = substr($product, 0, strrpos($product, '_'));
if (isset($result[$_product])) {
$result[$_product] += $qty; // we already started counting
} else {
$result[$_product] = $qty; // not started counting this product yet, start it
}
}
// now print your result:
foreach ($result as $id => $qty) {
echo $id, "\t", $qty, PHP_EOL;
}
I need some ideas for to do the follow:
I need to build a table dynamically and insert and update the data in the db with codeigniter.
$dates=array (date1, date2, ......daten) (cols)
$people=array(name1, name2, ......namen) (rows)
date1 date2 date3
name1 3 5 8
name2 2 6 9
name3 5 5 1
name4 10 2 8
In the db I need to register:
name1, date1 and 3
name1, date2 and 5
name2, date1 and 2
....
This solution has worked well for me, you just need to collate your array carefully.
(Taken from the PHP Cookbook)
function pc_grid_horizontal($array, $size) {
// compute <td> width %ages
$table_width = 100;
$width = intval($table_width / $size);
// define how our <tr> and <td> tags appear
// sprintf() requires us to use %% to get literal %
$tr = '<tr align="center">';
$td = "<td width=\"$width%%\">%s</td>";
// open table
$grid = "<table width=\"$table_width%%\">$tr";
// loop through entries and display in rows of size $sized
// $i keeps track of when we need a new table tow
$i = 0;
foreach ($array as $e) {
$grid .= sprintf($td, $e);
$i++;
// end of a row
// close it up and open a new one
if (!($i % $size)) {
$grid .= "</tr>$tr";
}
}
// pad out remaining cells with blanks
while ($i % $size) {
$grid .= sprintf($td, ' ');
$i++;
}
// add </tr>, if necessary
$end_tr_len = strlen($tr) * -1;
if (substr($grid, $end_tr_len) != $tr) {
$grid .= '</tr>';
} else {
$grid = substr($grid, 0, $end_tr_len);
}
// close table
$grid .= '</table>';
return $grid;
}
For example, let’s print the names of the 50 U.S. states in a six-column table:
$query = $this->db->query('SELECT * FROM `states`');
$states = $query->result_array();
// generate the HTML table
$grid = pc_grid_horizontal($states, 6);
print $grid;