How to remove existing values in array session using PHP? - php

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;
}

Related

PHP: shopping cart empty after clicking the add button

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>

Adding Totals to a Table According to Parameters in PHP

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;

What would be the best way to implode this associative array with keys and values

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

why tcpdf library output one record from loop?

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.

Get specific values from multidimentional array locked to ID

Maybe the title is a little confusing, but let me try to explain.
I have a database (informix), and use PHP PDO, in that database there is a table which contains stylesheets for pages.
See it like this:
Special ID, complete stylesheet (like we make it in a CSS file).
At the moment I can display the records in an multidimentional array (see below the code and output):
$query = $db -> prepare("select alpb_box_id, alpb_style::lvarchar as STYLESHEET
from ao_link_page_boxes WHERE alpb_li_id = 633 AND alpb_lngcode = '031' AND
alpb_pageno = 1");
$query -> execute();
$result = array();
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$result[] = $row;
}
$db = null;
echo "<pre>";
print_r($result);
echo "</pre>";
And the output:
Array
(
[0] => Array
(
[ALPB_BOX_ID] => TXT-633-P1B1
[STYLESHEET] => background-attachment:scroll; background-color:rgba(0, 0, 0, 0); background-image:none; background-position:0% 0%; background-repeat:repeat; border-bottom-color:rgb(0, 0, 0); border-bottom-style:none; border-bottom-width:0px; border-collapse:separate; border-left-color:rgb(0, 0, 0); border-left-style:none; border-left-width:0px; border-right-color:rgb(0, 0, 0); border-right-style:none; border-right-width:0px; border-top-color:rgb(0, 0, 0); border-top-style:none; border-top-width:0px; bottom:auto; box-shadow:none; caption-side:top; color:rgb(0, 0, 0); font-family:Swis721 BT; font-size:69px; font-style:normal; font-variant:normal; font-weight:normal; height:75px; left:0px; letter-spacing:normal; line-height:normal; list-style-image:none; list-style-position:outside; list-style-type:disc; margin-bottom:0px; margin-left:0px; margin-right:0px; margin-top:0px; max-height:none; max-width:none; min-height:0px; min-width:0px; overflow-x:hidden; overflow-y:hidden; padding-bottom:0px; padding-left:0px; padding-right:0px; padding-top:0px; position:relative; right:auto; text-align:-webkit-auto; text-decoration:none; text-indent:0px; text-overflow:clip; text-transform:none; top:0px; vertical-align:baseline; white-space:normal; width:793px; word-spacing:0px; z-index:auto;
)
[1] => Array
(
[ALPB_BOX_ID] => TXT-633-P1B2
[STYLESHEET] => background-attachment:scroll; background-color:rgba(0, 0, 0, 0); background-image:none; background-position:0% 0%; background-repeat:repeat; border-bottom-color:rgb(0, 0, 0); border-bottom-style:none; border-bottom-width:0px; border-collapse:separate; border-left-color:rgb(0, 0, 0); border-left-style:none; border-left-width:0px; border-right-color:rgb(0, 0, 0); border-right-style:none; border-right-width:0px; border-top-color:rgb(0, 0, 0); border-top-style:none; border-top-width:0px; bottom:auto; box-shadow:none; caption-side:top; color:rgb(0, 0, 0); font-family:\'Swis721 BT\'; font-size:16px; font-style:italic; font-variant:normal; font-weight:normal; height:197px; left:0px; letter-spacing:normal; line-height:normal; list-style-image:none; list-style-position:outside; list-style-type:disc; margin-bottom:0px; margin-left:0px; margin-right:0px; margin-top:0px; max-height:none; max-width:none; min-height:0px; min-width:0px; overflow-x:hidden; overflow-y:hidden; padding-bottom:0px; padding-left:0px; padding-right:0px; padding-top:0px; position:absolute; right:auto; text-align:-webkit-auto; text-decoration:none; text-indent:0px; text-overflow:clip; text-transform:none; top:75px; vertical-align:baseline; white-space:normal; width:717px; word-spacing:0px; z-index:auto;
)
[2] => Array
(
[ALPB_BOX_ID] => IMG-633-P1B3
[STYLESHEET] => background-attachment:scroll; background-color:rgba(0, 0, 0, 0); background-image:none; background-position:0% 0%; background-repeat:repeat; border-bottom-color:rgb(0, 0, 0); border-bottom-style:none; border-bottom-width:0px; border-collapse:separate; border-left-color:rgb(0, 0, 0); border-left-style:none; border-left-width:0px; border-right-color:rgb(0, 0, 0); border-right-style:none; border-right-width:0px; border-top-color:rgb(0, 0, 0); border-top-style:none; border-top-width:0px; bottom:auto; box-shadow:none; caption-side:top; color:rgb(0, 0, 0); font-family:\'Times New Roman\'; font-size:16px; font-style:normal; font-variant:normal; font-weight:normal; height:188px; left:0px; letter-spacing:normal; line-height:normal; list-style-image:none; list-style-position:outside; list-style-type:disc; margin-bottom:0px; margin-left:0px; margin-right:0px; margin-top:0px; max-height:none; max-width:none; min-height:0px; min-width:0px; overflow-x:visible; overflow-y:visible; padding-bottom:0px; padding-left:0px; padding-right:0px; padding-top:0px; position:relative; right:auto; text-align:-webkit-auto; text-decoration:none; text-indent:0px; text-overflow:clip; text-transform:none; top:207px; vertical-align:baseline; white-space:normal; width:377px; word-spacing:0px; z-index:auto;
)
[3] => Array
(
[ALPB_BOX_ID] => IMG-633-P1B4
[STYLESHEET] => background-attachment:scroll; background-color:rgba(0, 0, 0, 0); background-image:none; background-position:0% 0%; background-repeat:repeat; border-bottom-color:rgb(0, 0, 0); border-bottom-style:none; border-bottom-width:0px; border-collapse:separate; border-left-color:rgb(0, 0, 0); border-left-style:none; border-left-width:0px; border-right-color:rgb(0, 0, 0); border-right-style:none; border-right-width:0px; border-top-color:rgb(0, 0, 0); border-top-style:none; border-top-width:0px; bottom:auto; box-shadow:none; caption-side:top; color:rgb(0, 0, 0); font-family:Times New Roman; font-size:16px; font-style:normal; font-variant:normal; font-weight:normal; height:188px; left:0px; letter-spacing:normal; line-height:normal; list-style-image:none; list-style-position:outside; list-style-type:disc; margin-bottom:0px; margin-left:0px; margin-right:0px; margin-top:0px; max-height:none; max-width:none; min-height:0px; min-width:0px; overflow-x:visible; overflow-y:visible; padding-bottom:0px; padding-left:0px; padding-right:0px; padding-top:0px; position:relative; right:auto; text-align:-webkit-auto; text-decoration:none; text-indent:0px; text-overflow:clip; text-transform:none; top:0px; vertical-align:baseline; white-space:normal; width:377px; word-spacing:0px; z-index:auto;
)
)
Now what I try to do is, get from every ID (like: TXT-633-P1B1), the following styles:
height:75px;, width:793px;, top:0px; and left:0px;.
And store them into results so I can reuse and echo them when needed.
In this case I should get 4 ID's with 4 style items (including amount px).
Does anyone has an idea how to do this.
I hope I explained my question correct.
Thanks
Thanks that was very helpfull, I do have one question.
How can I add these values into an pre-made div.
For example:
<div id="TXT-633-P1B1" style="height:75px; width:793px; top:0px; left:0px;"></div>
And this for every ID that is in that array.
Thanks I really appreciate it.
Try this:
$new_styles = array();
$styles_to_collect = array('height', 'width', 'top', 'left');
foreach($result as $r)
{
$new_entry = array();
foreach($styles_to_collect as $stc)
{
preg_match('/[;\s]\s*'.$stc.':\s*([\d]+(px)?)([;\s]|$)/', $r['STYLESHEET'], $matches);
$new_entry[$stc] = $matches[1];
}
$new_styles[$r['ALPB_BOX_ID']] = $new_entry;
}
produces ($new_styles):
Array
(
[TXT-633-P1B1] => Array
(
[height] => 75px
[width] => 793px
[top] => 0px
[left] => 0px
)
[TXT-633-P1B2] => Array
(
[height] => 197px
[width] => 717px
[top] => 75px
[left] => 0px
)
[IMG-633-P1B3] => Array
(
[height] => 188px
[width] => 377px
[top] => 207px
[left] => 0px
)
[IMG-633-P1B4] => Array
(
[height] => 188px
[width] => 377px
[top] => 0px
[left] => 0px
)
)
EDIT: Per the OP's request I am adding more to my answer.
To use these styles in the content you could do something like:
$content = '';
foreach($new_styles as $id=>$ns)
{
$inline_styles = '';
foreach($ns as $name=>$value) $inline_styles .= $name.': '.$value.'; ';
$inline_styles = trim($inline_styles);
$content .= '<div id="'.$id.'" style="'.$inline_styles."\"></div>\n";
}
Which will set $content to:
<div id="TXT-633-P1B1" style="height: 75px; width: 793px; top: 0px; left: 0px;"></div>
<div id="TXT-633-P1B2" style="height: 197px; width: 717px; top: 75px; left: 0px;"></div>
<div id="IMG-633-P1B3" style="height: 188px; width: 377px; top: 207px; left: 0px;"></div>
<div id="IMG-633-P1B4" style="height: 188px; width: 377px; top: 0px; left: 0px;"></div>

Categories