i used TCPDF with codeigniter ,when PDF generated from sql query i got one record in the pdf file ,however,the table has three records...
print_r($pdf_data);
gave me this
Array ( [0] => Array ( [no] => 1 [name] => Jamal [address] => Ùخر ) [1] => Array ( [no] => 2 [name] => Jina [address] => Washington D.C ) [2] => Array ( [no] => 3 [name] => Dijandra [address] => Nairboi ) )
the controler
<?php
class example extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->library('pdf');
}
function b() {
$this->pdf->AddPage();
$font1 = $this->pdf->addTTFfont(K_PATH_FONTS . 'arial.ttf', 'TrueTypeUnicode', '', 8);
$this->pdf->SetFont($font1, '', 15, '', false);
$this->load->model('member_model');
$pdf_data = $this->member_model->alldata();
foreach ($pdf_data as $rows) {
$tbl = '<table style="width: 638px;" cellspacing="0">';
$id = $rows['no'];
$name = $rows['name'];
$address = $rows['address'];
$tbl .= '<tr>
<td style="border: 1px solid #000000; width: 150px;">' . $id . '</td>
<td style="border: 1px solid #000000; width: 378px;">' . $name . '</td>
<td style="border: 1px solid #000000; width: 110px; text-align:center">' . $address . '</td>
</tr>';
$tbl .= '</table>';
$this->pdf->writeHTML($tbl, true, false, false, false, '');
$this->pdf->Output('example_001.pdf', 'I');
}
}
?>
the model
<?php
class Member_model extends CI_Model {
function __construct() {
parent::__construct();
}
function alldata() {
$this->db->select('*')->from('tb_member')->order_by('no', 'ASC');
$getData = $this->db->get();
if ($getData->num_rows() > 0)
return $getData->result_array();
else
return NULL;
}
}
?>
From inside your foreach loop, remove the following segment:
$this->pdf->Output('example_001.pdf', 'I');
And put it outside the loop body.
Related
This question already has answers here:
Merge multiple associative arrays and add missing columns with a default value
(3 answers)
Closed 5 months ago.
I have an array with following format:
Array
(
[0] => Array
(
[Push to Web] => Yes
[attribute_set] => laminate_flooring
[category] => Accessories/Underlay
[name] => Under Pad Feather Light Foam
[sku] => 123-1028
[description] => Floor Underlayment Feather Light (Vapour Barrier) 200 Sqft/Roll
[short_description] => Floor Underlayment Feather Light (Vapour Barrier) 200 Sqft/Roll
[image] => 123-1028.jpg
[gallery_Image] => 9095307460638-424-424.jpg
[price] => 0.24
[qty_ca] => 16
[weight] => 3
[meta_description] => 51-1001
[meta_title] => Under Pad Feather Light Foam
[status] => 1
[flooring_coverage] => 200
[is_flooring_product] => 1
[web_price_comparative] => 0.31
)
[1] => Array
(
[Push to Web] => Yes
[category] => Accessories
[name] => Vent Maple Flush 4x10
[sku] => 089-1000
[description] => Vent Flush Mount Maple 4 x 10
[short_description] => Vent Flush Mount Maple 4 x 10
[image] => 089-1000.jpg
[price] => 17.05
[qty_ca] => 63
[qty_us] => 41
[meta_description] => 10-1023
[meta_title] => Vent Maple Flush 4x10
[status] => 1
[flooring_coverage] => 1
[min_order_qty] => 400
[web_price_comparative] => 22.16
)
)
I have to print the data in the table so that each key of array is printed as column header and the value as column data. That means Push to Web, attribute_set etc will be header and Yes, laminate_flooring will be data respectively.
I wrote the following but its not working.
$row = 0;
$table = '<table border="1" id="datatable">';
foreach($data as $value){
$table .= '<tr>';
if ($row == 0) {
foreach($value as $innerkey=>$innervalue){
$table .= '<td>'.$innerkey.'</td>';
}
}
$table .= '</tr><tr>';
foreach($value as $innerkey=>$innervalue){
$table .= '<td>'.$innervalue.'</td>';
}
$table .= '</tr>';
$row++;
}
$table .= '</table>';
print_r($table);
The output of the table should be as follows:
But is is showing like this
First problem is the header row is continue printing only upto avalable data in first data row. Secondly If any data cell is unavailable then it is filled by next cell data. but it is supposed to be remain bank cell.
Please help me to sort out the problem. Thanks in advance
<?php declare(strict_types=1);
/**
* Flatting the uniqueness of all headers, which might be different
* from the different arrays
*/
function uniqueHeaders(array $allArrays): array
{
return array_unique(
call_user_func_array('array_merge', // flatting one level all keys
array_map(function (array $a): array {
return array_keys($a);
}, $allArrays)
)
);
}
/**
* Normalize that all arrays contain the same headers.
* Filling with an empty string the headers that don't exists from
* the others.
*/
function normalizeHeaders(array $allArrays): array
{
$headers = uniqueHeaders($allArrays);
foreach ($allArrays as &$array) {
foreach ($headers as $header) {
if (!isset($array[$header])) {
$array[$header] = '';
}
}
}
array_map('ksort', $allArrays);
return $allArrays;
}
/**
* This function generates the table as HTML with all array
* values as they come. No special "business logic" behind.
*/
function generateTable(array $allArrays): string
{
$headers = uniqueHeaders($allArrays);
$table = '<table border="1" id="datatable">';
$table .= '<tr>';
// first the headers
foreach ($headers as $header) {
$table .= '<th>' . $header . '</th>';
}
$table .= '</tr>';
// then the values
foreach ($allArrays as $value) {
$table .= '<tr>';
foreach ($value as $innervalue) {
$table .= '<td>' . $innervalue . '</td>';
}
$table .= '</tr>';
}
$table .= '</table>';
return $table;
}
// Usage example using different headers from each array:
$allArrays = [
[
'header1' => 'value11',
'header2' => 'value12',
'header3' => 'value13',
'header4' => 'value14',
'header7' => 'value17',
],
[
'header1' => 'value21',
'header2' => 'value22',
'header5' => 'value25',
'header6' => 'value26',
],
];
$normalized = normalizeHeaders($allArrays);
$table = generateTable($normalized);
print $table . PHP_EOL;
// Unit test:
$result = <<<HTML
<table border="1" id="datatable">
<tr>
<th>header1</th><th>header2</th><th>header3</th><th>header4</th><th>header5</th><th>header6</th><th>header7</th>
</tr>
<tr>
<td>value11</td><td>value12</td><td>value13</td><td>value14</td><td></td><td></td><td>value17</td>
</tr>
<tr>
<td>value21</td><td>value22</td><td></td><td></td><td>value25</td><td>value26</td><td></td>
</tr>
</table>
HTML;
// Result removing all spaces per line and unifying everything in one line (as the generateTable())
$expected = implode('', array_map('trim', explode(PHP_EOL, $result)));
assert($expected === $table);
This assumes that all the child arrays use the same keys, which from the picture it looks like they do.
Also I've added htmlentities just to stop any rogue html breaking the table, but you can remove it if you know it's not needed.
$table = '<table border="1" id="datatable"><tr>';
// Get the headers from the first child array.
$headers = array_keys($data[0]);
foreach($headers as $header){
$table .= '<th>'.htmlentities($header).'</th>';
}
foreach($data as $value){
$table .= '</tr><tr>';
foreach($value as $innerkey=>$innervalue){
$table .= '<td>'.htmlentities($innervalue).'</td>';
}
$table .= '</tr>';
}
$table .= '</table>';
As per title, I have a problem when adding products to the cart: it would show a window message that says that the product has been added, but in truth it is not there. It gives the following error:
Fatal error: Cannot use object of type stdClass as array
the line is: <td><?php echo $value['item_name']; ?></td>
Here is the code file reserve.php :
<?php
session_start();
ini_set('display_errors', 1);
$connect = mysqli_connect('127.0.0.1', 'root', '***********', 'Community Garden List');
if (isset($_POST['add'])) {
if (isset($_SESSION['cart'])) {
$item_array_id = array_column($_SESSION['cart'], 'product_id');
if (!in_array($_GET['id'], $item_array_id)) {
$count = count($_SESSION['cart']);
$item_array = array(
'product_id' => $_GET['id'],
'item_name' => $_POST['hidden_name'],
'product_price' => $_POST['hidden_price'],
'item_quantity' => $_POST['quantity'],
);
$_SESSION['cart'][$count] = $item_array;
echo '<script>window.location="reserve.php"</script>';
} else {
echo '<script>alert("Product is already Added to Cart")</script>';
echo '<script>window.location="reserve.php"</script>';
}
} else {
$item_array = array(
'product_id' => $_GET['id'],
'item_name' => $_POST['hidden_name'],
'product_price' => $_POST['hidden_price'],
'item_quantity' => $_POST['quantity'],
);
$_SESSION['cart'][0] = $item_array;
}
}
if (isset($_GET['action'])) {
if ($_GET['action'] == 'delete') {
foreach ($_SESSION['cart'] as $keys => $value) {
if ($value['product_id'] == $_GET['id']) {
unset($_SESSION['cart'][$keys]);
echo '<script>alert("Product has been Removed...!")</script>';
echo '<script>window.location="reserve.php"</script>';
}
}
}
}
?>
?>
html code
<?php
$query = 'SELECT * FROM product ORDER BY serial ASC';
$result = mysqli_query($connect, $query);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
?>
<div class="col-md-4">
<form method="post" action="reserve.php?action=add&id='.$row['id'].">
<div style="border: 1px solid #eaeaec; margin: -1px 19px 3px -1px; box-shadow: 0 1px 2px rgba(0,0,0,0.05); padding:10px;" align="center">
<img src="<?php echo $row['image']; ?>" class="img-responsive" style="width:100%;>
<h5 class="text-info"><?php echo $row['pname']; ?></h5>
<h5 class="text-danger">€ <?php echo $row['price']; ?></h5>
<h5 class="text-info"><?php echo $row['pdescription']; ?></h5>
<input type="text" name="quantity" class="form-control" value="1">
<input type="hidden" name="hidden_name" value="<?php echo $row['pname']; ?>">
<input type="hidden" name="hidden_price" value="<?php echo $row['price']; ?>">
<input type="hidden" name="hidden_pdescription" value="<?php echo $row['pdescription']; ?>">
<input type="submit" name="add" style="margin-top:5px;" class="btn btn-success" value="Add to Bag">
</div>
</form>
</div>
}
}
?>
<?php
if(!empty($_SESSION["cart"])){
$total = 0;
foreach ($_SESSION["cart"] as $key => $value) {
?>
<tr>
<td><?php echo $value["item_name"]; ?></td>
<td><?php echo $value["item_quantity"]; ?></td>
<td>$ <?php echo $value["product_price"]; ?></td>
<td>
$ <?php echo number_format($value["item_quantity"] * $value["product_price"], 2); ?></td>
<td><a href="Cart.php?action=delete&id=<?php echo $value["product_id"]; ?>"><span
class="text-danger">Remove Item</span></a></td>
</tr>
<?php
$total = $total + ($value["item_quantity"] * $value["product_price"]);
}
?>
<tr>
<td colspan="3" align="right">Total</td>
<th align="right">$ <?php echo number_format($total, 2); ?></th>
<td></td>
</tr>
<?php
}
?>
</table>
</div>
</div>
I've tried print "<pre>"; var_dump($row); exit; after this line: foreach e($_SESSION['cart'] as $key => $value) { and it comes a table with NULL inside. What does that mean?
Before that, i tried to change $value['item_name'] with $value->item_name , and i got the following error:
Notice: Undefined property: stdClass::$item_name in
Will you please help me to understand what's wrong? thank you.
i solve some errors try to assemble the parts in the right places
i put all content modified here you should copy paste parts you need.
<?php
session_start();
ini_set('display_errors', 1);
$connect = mysqli_connect('127.0.0.1', 'root', '******************', 'Community Garden List');
if (isset($_POST['add'])) {
if (isset($_SESSION['cart'])) {
$item_array_id = array_column($_SESSION['cart'], 'product_id');
if (!in_array($_GET['id'], $item_array_id)) {
$count = count($_SESSION['cart']);
$item_array = array(
'product_id' => $_GET['id'],
'item_name' => $_POST['hidden_name'],
'product_price' => $_POST['hidden_price'],
'item_quantity' => $_POST['quantity']//!!!,
);
$_SESSION['cart'][$count] = $item_array;
//echo '<script>window.location="reserve.php"</script>';// do not send content when you use sessions $_SESSION['cart'][0] = $item_array;
} else {
// echo '<script>alert("Product is already Added to Cart")</script>';
//echo '<script>window.location="reserve.php"</script>';
}
} else {
$item_array = array(
'product_id' => $_GET['id'],
'item_name' => $_POST['hidden_name'],
'product_price' => $_POST['hidden_price'],
'item_quantity' => $_POST['quantity']//!!!!!!!!!!!! ? ->,
);
$_SESSION['cart'][0] = $item_array;
}
}
if (isset($_GET['action'])) {
if ($_GET['action'] == 'delete') {
foreach ($_SESSION['cart'] as $keys => $value) {
if ($value['product_id'] == $_GET['id']) {
unset($_SESSION['cart'][$keys]);
echo '<script>alert("Product has been Removed...!")</script>';
echo '<script>window.location="reserve.php"</script>';
}
}
}
}
$query = 'SELECT * FROM product ORDER BY serial ASC';
$result = mysqli_query($connect, $query);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
die();
$tmimi1=<<<mimi1
<div class="col-md-4">
<form method="post" action="reserve.php?action=add&id={$row['id']}">
<div style="border: 1px solid #eaeaec; margin: -1px 19px 3px -1px; box-shadow: 0 1px 2px rgba(0,0,0,0.05); padding:10px;" align="center">
<img src="{$rr1}" class="img-responsive" style="width:100%;">
<h5 class="text-info">{$row['pname']}</h5>
<h5 class="text-danger">€{$row['price']}</h5>
<h5 class="text-info">{$row['pdescription']}</h5>
<input type="text" name="quantity" class="form-control" value="1">
<input type="hidden" name="hidden_name" value="{$row['pname']}">
<input type="hidden" name="hidden_price" value="{$row['price']}">
<input type="hidden" name="hidden_pdescription" value="{$row['pdescription']}">
<input type="submit" name="add" style="margin-top:5px;" class="btn btn-success" value="Add to Bag">
</div>
</form>
</div>
mimi1;
}
}
echo($tmimi1);
if(!empty($_SESSION["cart"])){
$total = 0;
foreach ($_SESSION["cart"] as $key => $value) {
$tmimi2 =<<<mimi2
<tr>
<td>{$value["item_name"]}</td>
<td>{$value["item_quantity"]}</td>
<td>${$value["product_price"]}</td>
<td>$
mimi2;
echo($tmimi2);
echo number_format($value["item_quantity"] * $value["product_price"], 2);
$tmimi2=<<<mimi3
</td>
<td><a href="Cart.php?action=delete&id={$value["product_id"]}"><span
class="text-danger">Remove Item</span></a></td>
</tr>
mimi3;
echo($tmimi3);
$total = $total + ($value["item_quantity"] * $value["product_price"]);
}
$tmimi2=<<<mimi4
<tr>
<td colspan="3" align="right">Total</td>
<th align="right">$
mimi4;
echo($tmimi4);
echo number_format($total, 2);
$tmimi2=<<<mimi5
</th>
<td></td>
</tr>
mimi5;
echo($tmimi5); }
$tmimi2=<<<mimi6
</table>
</div>
</div>
mimi6;
echo($tmimi6);
?>
you deleted your post about grab an array from online weather data before to post you the answer? i don't know how to send you what you ask and then you delete the question before to push 'post the answer' button!(if was you mimi who ask or there is another mimi=not sure) in case you ask before that i post you the answer:
<?php
function print_r2($var){
echo('<h3>'.$var.':</h3><br>');
print_r($GLOBALS[$var]);echo('br');
}
function hr(){
echo('<hr>');
}
$lines=implode(file('http://samples.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=b6907d289e10d714a6e88b30761fae22'));
print_r2('lines');hr();
$data = json_decode($lines);
print_r2('data');hr();
print('wind obj:');print_r($data->wind);hr();
print('speed:');print_r($data->wind->speed);hr();
print('deg:');print_r($data->wind->deg);hr();
?>
and on my screen i got ..push RUN CODE SNIPPET!
<h3>lines:</h3><br>{"coord":{"lon":139.01,"lat":35.02},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}],"base":"stations","main":{"temp":285.514,"pressure":1013.75,"humidity":100,"temp_min":285.514,"temp_max":285.514,"sea_level":1023.22,"grnd_level":1013.75},"wind":{"speed":5.52,"deg":311},"clouds":{"all":0},"dt":1485792967,"sys":{"message":0.0025,"country":"JP","sunrise":1485726240,"sunset":1485763863},"id":1907296,"name":"Tawarano","cod":200}br<hr><h3>data:</h3><br>stdClass Object
(
[coord] => stdClass Object
(
[lon] => 139.01
[lat] => 35.02
)
[weather] => Array
(
[0] => stdClass Object
(
[id] => 800
[main] => Clear
[description] => clear sky
[icon] => 01n
)
)
[base] => stations
[main] => stdClass Object
(
[temp] => 285.514
[pressure] => 1013.75
[humidity] => 100
[temp_min] => 285.514
[temp_max] => 285.514
[sea_level] => 1023.22
[grnd_level] => 1013.75
)
[wind] => stdClass Object
(
[speed] => 5.52
[deg] => 311
)
[clouds] => stdClass Object
(
[all] => 0
)
[dt] => 1485792967
[sys] => stdClass Object
(
[message] => 0.0025
[country] => JP
[sunrise] => 1485726240
[sunset] => 1485763863
)
[id] => 1907296
[name] => Tawarano
[cod] => 200
)
br<hr>wind obj:stdClass Object
(
[speed] => 5.52
[deg] => 311
)
<hr>speed:5.52<hr>deg:311<hr>
I have this code to show a table in PHP:
<?php
$harvest = Array (
Array (
Array (
'PRODUCT' => 'ROSE' ,
'VARIETY' => 'ADELE',
'GOLD' => 160,
'NORMAL' => 0 ,
'TOTAL' => 160
) ,
Array (
'PRODUCT' => 'ROSE',
'VARIETY' => 'ALESSO' ,
'GOLD' => 1320 ,
'NORMAL' => 550,
'TOTAL' => 1870
) ,
Array (
'PRODUCT' => 'ROSE',
'VARIETY' => 'ANASTACIA' ,
'GOLD' => 440 ,
'NORMAL' => 150 ,
'TOTAL' => 590
),
Array (
'PRODUCT' => 'ROSE1',
'VARIETY' => 'ANASTACIA1' ,
'GOLD' => 420 ,
'NORMAL' => 120 ,
'TOTAL' => 540
),
Array (
'PRODUCT' => 'ROSE1',
'VARIETY' => 'ANASTACIA1',
'GOLD' => 440 ,
'NORMAL' => 100 ,
'TOTAL' => 540
),
Array (
'PRODUCT' => 'ROSE2',
'VARIETY' => 'ANASTACIA2',
'GOLD' => 640,
'NORMAL' => 0,
'TOTAL' => 640
),
Array (
'PRODUCT' => 'ROSE2',
'VARIETY' => 'ANASTACIA2' ,
'GOLD' => 440,
'NORMAL' => 440,
'TOTAL' => 880
)
)
);
$arrayThead = array();
for ($i=0; $i < count($harvest) ; $i++) {
array_push($arrayThead, array_keys($harvest[$i][0]));
}
$totalByProduct = array();
foreach ($harvest as $items) {
foreach ($items as $item) {
if(!key_exists($item['PRODUCT'], $totalByProduct)){
$totalByProduct[$item['PRODUCT']] = $item;
unset($totalByProduct[$item['PRODUCT']]['VARIETY']);
continue;
}
foreach ($arrayThead as $key => $values) {
foreach ($values as $th) {
if($th != 'PRODUCT' && $th != 'VARIETY'){
$totalByProduct[$item['PRODUCT']][$th] += $item[$th];
}
}
}
}
}
$arrayfoot= array();
foreach ($harvest as $key => $value) {
foreach ($value as $harv) {
foreach ($arrayThead as $key => $values) {
foreach ($values as $th) {
if($th != 'PRODUCT' && $th != 'VARIETY'){
$arrayfoot[$th] += $harv[$th];
}
}
}
}
}
$arrayfoot= array();
foreach ($harvest as $key => $value) {
foreach ($value as $harv) {
foreach ($arrayThead as $key => $values) {
foreach ($values as $th) {
if($th != 'PRODUCT' && $th != 'VARIETY'){
$arrayfoot[$th] += $harv[$th];
}
}
}
}
}
$arrayComplete = array();
for ($i=0; $i < count($arrayThead) ; $i++) {
for ($j=0; $j < count($arrayThead[$i]) ; $j++) {
if($arrayThead[$i][$j] != 'PRODUCT' && $arrayThead[$i][$j] != 'VARIETY'){
array_push($arrayComplete, $arrayThead[$i][$j]);
}
}
}
$arrayFinal = array();
for ($j=0; $j < count($arrayComplete) ; $j++) {
array_push($arrayFinal, $arrayfoot[$arrayComplete[$j]]);
}
// exit;
$body = '';
$body .= '<table style="border: 1px solid black;border-collapse: collapse;width: 100%;font-family:Calibri;">';
$body .= '<thead style="background-color:#f3f4f5;">';
$body .= '<tr>';
for ($i=0; $i < count($arrayThead) ; $i++) {
for ($j=0; $j < count($arrayThead[$i]) ; $j++) {
if($arrayThead[$i][$j] === 'PRODUCT' || $arrayThead[$i][$j] === 'VARIETY'){
$body .= '<th style="border: 1px solid black;height:50px;">'.$arrayThead[$i][$j].'</th>';
}else{
$body .= '<th style="border: 1px solid black;height:50px;">'.$arrayThead[$i][$j].'</th>';
}
}
}
$body .= '</tr>';
$body .= '</thead>';
$body .= '<tbody>';
for ($k=0; $k < count($harvest); $k++) {
for ($a=0; $a < count($harvest[$k]) ; $a++) {
$body .= '<tr>';
for ($i=0; $i < count($arrayThead) ; $i++) {
for ($j=0; $j < count($arrayThead[$i]) ; $j++) {
if($arrayThead[$i][$j] === 'PRODUCT' || $arrayThead[$i][$j] === 'VARIETY'){
$body .= '<td style="border: 1px solid black;font-size:12px;">'.$harvest[$k][$a][$arrayThead[$i][$j]].'</td>';
}else{
$body .= '<td style="border: 1px solid black; text-align:right;font-size:12px;">'.number_format($harvest[$k][$a][$arrayThead[$i][$j]]).'</td>';
}
}
}
$body .= '</tr>';
foreach ($totalByProduct as $key => $value) {
if($value["PRODUCT"] == $harvest[$k][$a]['PRODUCT']){
$body .= '<tr>';
$body .= '<th style="border: 1px solid black;text-align:left;font-size:12px;">TOTAL '.$value["PRODUCT"].'</th>';
$body .= '<th style="border: 1px solid black;text-align:left;font-size:12px;"></th>';
foreach ($arrayThead as $key => $values) {
foreach ($values as $th) {
if($th != 'PRODUCT' && $th != 'VARIETY'){
$body .= '<th style="border: 1px solid black;text-align:right;font-size:12px;">'.number_format($value[$th]).'</th>';
}
}
}
$body .= '</tr>';
}
}
}
}
$body .= '</tbody>';
$body .= '<tfoot>';
$body .= '<tr>';
$body .= '<th style="border: 1px solid black;text-align:left;">TOTAL GENERAL</th>';
$body .= '<th style="border: 1px solid black;"></th>';
for ($i=0; $i < count($arrayFinal) ; $i++) {
$body .= '<th style="border: 1px solid black;text-align:right;">'.number_format($arrayFinal[$i]).'</th>';
}
$body .= '</tr>';
$body .= '</tfoot>';
$body .= '</table>';
echo $body;
I need to place a row with the total of GOLD, NORMAL and TOTAL inside the table, but according the product.
If you want to see how the code works you can copy the code and past in this page: PHPTESTER
I need to show the table something like this:
-------------------------------------------------------------------
PRODUCT | VARIETY | GOLD | NORMAL | TOTAL |
-------------------------------------------------------------------
ROSE | ADELE | 160 | 0 | 160 |
-------------------------------------------------------------------
ROSE | ALESSO | 1320 | 550 | 1870 |
-------------------------------------------------------------------
ROSE | ANASTACIA | 440 | 150 | 590 |
-------------------------------------------------------------------
TOTAL ROSE | | 1920 | 700 | 2620 |
-------------------------------------------------------------------
ROSE1 | ANASTACIA1 | 420 | 120 | 540 |
-------------------------------------------------------------------
ROSE1 | ANASTACIA1 | 440 | 100 | 540 |
-------------------------------------------------------------------
TOTAL ROSE1 | | 860 | 220 | 1080 |
-------------------------------------------------------------------
ROSE2 | ANASTACIA2 | 640 | 0 | 640 |
-------------------------------------------------------------------
ROSE2 | ANASTACIA2 | 440 | 440 | 880 |
-------------------------------------------------------------------
TOTAL ROSE2 | | 1080 | 440 | 1520 |
-------------------------------------------------------------------
TOTAL GENERAL| | 3860 | 1360 | 5220 |
-------------------------------------------------------------------
I hope that someone can help me thanks!
Here is the code. You can make modification to the code
foreach($harvest[0] as $key=>$value){
$new_array[$value['PRODUCT']][] = $value;
}
echo '<table cellspacing="5" cellpadding="5" border="1px solid #ccc">';
echo "<tr>
<th>PRODUCT</th>
<th>VARIETY</th>
<th>GOLD</th>
<th>NORMAL</th>
<th>TOTAL</th>
</tr>";
$total_gold = $total_normal = $total_total = 0;
foreach($new_array as $key=>$value){
$gold[$key] = $normal[$key] = $total[$key] = 0;
if(is_array($value)){
foreach($value as $k=>$v){
$gold[$key] += $v['GOLD'];
$normal[$key] += $v['NORMAL'];
$total[$key] += $v['TOTAL'];
echo "<tr>";
echo "<td>".$key."</td>";
echo "<td>".$v['VARIETY']."</td>";
echo "<td>".$v['GOLD']."</td>";
echo "<td>".$v['NORMAL']."</td>";
echo "<td>".$v['TOTAL']."</td>";
echo "<tr>";
}
echo "<tr><td><b>Total ".$key."</b></td><td></td><td>".$gold[$key]."</td><td>".$normal[$key]."</td><td>".$total[$key]."</td></tr>";
$total_gold +=$gold[$key];
$total_normal +=$normal[$key];
$total_total += $total[$key];
}
}
echo "<tr><td><b>TOTAL GENERAL</b></td><td></td><td>".$total_gold."</td><td>".$total_normal."</td><td>".$total_total."</td></tr>";
echo "</table>";
<?php
$harvest = Array (
Array (
Array (
'PRODUCT' => 'ROSE' ,
'VARIETY' => 'ADELE',
'GOLD' => 160,
'NORMAL' => 0 ,
'TOTAL' => 160
) ,
Array (
'PRODUCT' => 'ROSE',
'VARIETY' => 'ALESSO' ,
'GOLD' => 1320 ,
'NORMAL' => 550,
'TOTAL' => 1870
) ,
Array (
'PRODUCT' => 'ROSE',
'VARIETY' => 'ANASTACIA' ,
'GOLD' => 440 ,
'NORMAL' => 150 ,
'TOTAL' => 590
),
Array (
'PRODUCT' => 'ROSE1',
'VARIETY' => 'ANASTACIA1' ,
'GOLD' => 420 ,
'NORMAL' => 120 ,
'TOTAL' => 540
),
Array (
'PRODUCT' => 'ROSE1',
'VARIETY' => 'ANASTACIA1',
'GOLD' => 440 ,
'NORMAL' => 100 ,
'TOTAL' => 540
),
Array (
'PRODUCT' => 'ROSE2',
'VARIETY' => 'ANASTACIA2',
'GOLD' => 640,
'NORMAL' => 0,
'TOTAL' => 640
),
Array (
'PRODUCT' => 'ROSE2',
'VARIETY' => 'ANASTACIA2' ,
'GOLD' => 440,
'NORMAL' => 440,
'TOTAL' => 880
)
)
);
$prods = array();
$prevprod = "";
$total_gold = 0;
$total_normal = 0;
$total_prod = 0;
$total = 0;
foreach($harvest[0] as $key => $val){
$pos = $key;
$obj = $val;
$total_prod = $obj["GOLD"]+$obj["NORMAL"];
if($obj["PRODUCT"]==$prevprod || $prevprod==""){
$prods[] = array($obj["PRODUCT"],$obj["VARIETY"],$obj["GOLD"],$obj["NORMAL"],$obj["TOTAL"]);
$total_gold = $total_gold + $obj["GOLD"];
$total_normal = $total_normal + $obj["NORMAL"];
$total_prod = $total_prod + $obj["TOTAL"];
$total = $total + $total_prod;
}else{
$prods[] = array( "TOTAL ".$prevprod, "", $total_gold,$total_normal,$total_prod);
$total_gold = 0;
$total_normal = 0;
$total_prod = 0;
}
$prevprod = $obj["PRODUCT"];
}
$prods[] = array( "TOTAL ".$prevprod, "", $total_gold,$total_normal,$total_prod);
// exit;
$body = '';
$body .= '<table style="border: 1px solid black;border-collapse: collapse;width: 100%;font-family:Calibri;">';
$body .= '<thead style="background-color:#f3f4f5;">';
$body .= '<tr>';
$body .= '<th>PRODUCT</th><th>VARIETY</th><th>GOLD</th><th>NORMAL</th><th>TOTAL</th>';
$body .= '</tr>';
$body .= '</thead>';
$body .= '<tbody>';
foreach($prods as $p){
$body .= '<tr><td>'.$p[0].'</td><td>'.$p[1].'</td><td>'.$p[2].'</td><td>'.$p[3].'</td><td>'.$p[4].'</td><tr>';
}
$body .= '</tbody>';
$body .= '<tfoot>';
$body .= '<tr>';
$body .= '<th style="border: 1px solid black;text-align:left;">TOTAL GENERAL</th>';
$body .= '<th style="border: 1px solid black;"></th><th style="border: 1px solid black;"></th><th style="border: 1px solid black;"></th>';
$body .= '<th>'.$total.'</th>';
$body .= '</tr>';
$body .= '</tfoot>';
$body .= '</table>';
echo $body;
I have a box model array
Array
(
[padding] => Array
(
[padding-top] => 0px
[padding-right] => 0px
[padding-bottom] => 0px
[padding-left] => 0px
)
[margin] => Array
(
[margin-top] => 0px
[margin-right] => 0px
[margin-bottom] => 0px
[margin-left] => 0px
)
[border] => Array
(
[border-size] => 0px
[border-style] => solid
[border-color] => #ff6600
)
)
And I need to output the following
padding-top : 0px;
padding-right: 0px;
padding-bottom: 0px;
padding-left: 0px;
margin-top : 0px;
margin-right: 0px;
margin-bottom: 0px;
margin-left: 0px;
border-size : 0px;
border-style: solid;
border-color: #ff6600;
I started with this
$box_model = array();
foreach($box_model_array as $key => $value){
$box_model[$key] = $key.':'.implode(';',$value).'';
}
return implode('',$box_model);
so I ended up missing the second array index.
What would be the fastest way to get the desired result?
Any help is appreciated.
Try this:
$box_model = array();
foreach ($box_model_array as $group => $styles) {
foreach ($styles as $name => $value) {
$box_model[] = "$name: $value;";
}
// If you really need the space in between the groups.
$box_model[] = "";
}
$box_model = implode("\n", $box_model);
Can you help me with my code. I am creating a super simple shopping cart that can add cart/update and remove. But as for now what I already did is the add to cart and the displaying of items. But I have an error. Everytime I refresh the page the session is automatically appending to the session array.
Now what I need to do is this.
Validate if the product is in the session list. If not create a session for that if yes just skip it.
And for the additional question. How can I create an update/remove function?
Here's my code so far. This process is only 1 PHP file.
$category = $_GET['cat'];
$product_id = $_GET['product'];
//fn_print_r($_SESSION);
//unset($_SESSION['cart']);
$product_detail = get_allproduct_detail($product_id);
$prod_price = $product_detail['prod_price'];
$sale_price = $product_detail['sale_price'];
$prod_type = $product_detail['prod_type'];
if(!empty($_POST['product_id']) && !empty($_POST['product_name']) && !empty($_POST['product_price']) && !empty($_POST['sale_price']) && !empty($_POST['qty'])) {
$sess_id = $_POST['product_id'];
$sess_name = $_POST['product_name'];
$sess_price = $_POST['product_price'];
$sess_sale_price = $_POST['sale_price'];
$sess_qty = $_POST['qty'];
$compute_total = $sess_sale_price * $sess_qty;
$cart_row = array(
'product_id' => $sess_id,
'product_name' => $sess_name,
'product_price' => $sess_price,
'sale_price' => $sess_sale_price,
'qty' => $sess_qty,
'total' => $compute_total
);
if(!isset($_SESSION['cart'])){
$_SESSION['cart'] = array();
}
$_SESSION['cart'][] = $cart_row;
//fn_print_r($_SESSION);
}
Here's the form process
<form method="POST" action="?page=product&cat=<?php echo $_GET['cat']; ?>&product=<?php echo $_GET['product']; ?>" onsubmit="">
<div id="item_detail_right">
<label>Qty:<input type="text" name="qty" value="1" size="5" style="text-align: center" />
<input type="hidden" name="product_price" id="product_price" value="<?php echo $prod_price; ?>" />
<input type="hidden" name="sale_price" id="sale_price" value="<?php echo $sale_price; ?>" />
<input type="hidden" name="product_id" id="product_id" value="<?php echo $_GET['product']; ?>" />
<input type="hidden" name="product_name" id="product_name" value="<?php echo strtoupper(get_product_name($_GET['product'])); ?>" />
<input type="submit" value="+CART" />
<input type="button" value="+Wishlist" id="mywishlist" data-wishlist-id="<?php echo $_GET['product']; ?>" />
</div>
</form>
Here's the display of cart
if(!isset($_SESSION['cart']) || (count($_SESSION['cart']) == 0)) {
echo "<p>Your cart is empty</p>";
} else {
echo "<table border='0' style='font-size: 12px; width: 100%' cellpadding='5'>";
echo "<tr>";
echo "<td style='background-color: white; color: black; text-align: center'>Product ID</td>";
echo "<td style='background-color: white; color: black; text-align: center'>Name</td>";
echo "<td style='background-color: white; color: black; text-align: center'>Price</td>";
echo "<td style='background-color: white; color: black; text-align: center'>Sale Price</td>";
echo "<td style='background-color: white; color: black; text-align: center'>Quantity</td>";
echo "<td style='background-color: white; color: black; text-align: center'>Total</td>";
echo "<td style='background-color: white; color: black; text-align: center'></td>";
echo "</tr>";
$total = 0;
foreach($_SESSION['cart'] as $item) {
echo "<tr>";
echo "<td style='text-align: center; background-color: gray; color: black'>".$item['product_id']."</td>";
echo "<td style='text-align: left; background-color: gray; color: black'>".$item['product_name']."</td>";
echo "<td style='text-align: right; background-color: gray; color: black'>".number_format($item['product_price'],2)."</td>";
echo "<td style='text-align: right; background-color: gray; color: black'>".number_format($item['sale_price'],2)."</td>";
echo "<td style='text-align: center; background-color: gray; color: black'><input type='text' name='cart_qty[]' value='".$item['qty']."' size='10' style='text-align: center'></td>";
echo "<td style='text-align: right; background-color: gray; color: black'>".number_format($item['total'],2)."</td>";
echo "<td style='text-align: center; background-color: gray; color: black'><a href='#'>Update this?</a> | <a href='#'>Remove this?</div></td>"; //how can I use this to remove and update the session?
echo "</tr>";
$total += ($item['sale_price'] * $item['qty']);
}
echo "<tr>";
echo "<td colspan='7' style='text-align: right'>";
echo "<label>Subtotal Amount: </label><input type='text' name='subtotal' value='".number_format($total,2)."' readonly='readonly'>";
echo "<input type='submit' value='Place Item' />";
echo "</td>";
echo "</tr>";
echo "</table>";
}
Here's my sample output of array
Array
(
[visit] => nsrAROum86lb8VK
[slideshow] => 04-15-14
[cart] => Array
(
[0] => Array
(
[product_id] => 1
[product_name] => AJNA
[product_price] => 90
[sale_price] => 81
[qty] => 1
[total] => 81
)
[1] => Array
(
[product_id] => 1
[product_name] => AJNA
[product_price] => 90
[sale_price] => 81
[qty] => 1
[total] => 81
)
[2] => Array
(
[product_id] => 1
[product_name] => AJNA
[product_price] => 90
[sale_price] => 81
[qty] => 1
[total] => 81
)
[3] => Array
(
[product_id] => 1
[product_name] => AJNA
[product_price] => 90
[sale_price] => 81
[qty] => 1
[total] => 81
)
)
)
i uploaded my whole code to this link
http://www.mediafire.com/view/g6jah2bxbzda04l/aroma_shop.php
You can check wether the product is already in the cart.
if(!isset($_SESSION['cart'])){
$_SESSION['cart'] = array();
}
// Instead of appending $cart_row immediately,
// $_SESSION['cart'][] = $cart_row;
// only add the $cart_row which has not been added previously
$found = false;
foreach ($_SESSION['cart'] as $c) {
if ($c['product_id'] == $cart_row['product_id']) {
$found = true;
}
}
if (!$found) {
$_SESSION['cart'][] = $cart_row;
}