I want to count my $_SESSION['cart'] (units) products from my basket.
#check added stock
$units = (int) $_POST['units'];
$sizes_id = (int) $_POST['size_id'];
$in_stock = $db->GetScalar("SELECT p.units FROM products_sizes s
INNER JOIN products p ON p.product_id = s.product_id
WHERE s.id = '$sizes_id' LIMIT 1");
$total = isset($_SESSION['cart'][$sizes_id]) ? $_SESSION['cart'][$sizes_id]['units'] : 0;
$total += $units;
if($total <= $in_stock) {
if(isset($_SESSION['cart'][$sizes_id])) {
$_SESSION['cart'][$sizes_id]['units'] = $total;
} else {
$_SESSION['cart'][$sizes_id] = array('size' => $sizes_id, 'units' => $total);
}
$msg = 'Added';
$status = 1;
}else {
$msg = 'Product is not in the basket';
$status = 0;
}
This is how the output looks like
Array(
[57] => Array
(
[size] => 57
[units] => 5
)
[56] => Array
(
[size] => 56
[units] => 1
)
)
Ok here goes
<?php
$total_units = 0;
foreach ($_SESSION['cart'] as $key => $value) {
$total_units += $value['units'];
}
echo $total_units;
?>
Should get the answer
This should do the job:
$numUnits = 0;
foreach ($yourArray as $item)
$numUnits += $item['units'];
Related
So what I want to do is get all values from query and add them together to get a total amount. The following function grabs all values necessary. (Added for clarity)
public function priceTotal($conn, $var, $hours){
$query = "SELECT hour_rate, day_rate, item_id, hourly_rental FROM products WHERE item_id = :id";
$stmt = $conn->prepare($query);
$stmt->bindParam(":id", $var);
$stmt->execute();
$result = $stmt->fetchAll();
if($stmt->rowCount() > 0){
$total = 0;
foreach($result as $row){
$hour_rate = $row['hour_rate'];
$day_rate = $row['day_rate'];
if($hours == '2'){
$total += $hour_rate;
}else{
if($row['hourly_rental'] == '1'){
$hours -= 2;
$total += $hour_rate + $day_rate * $hours;
}
else{
$total = $hour_rate + $day_rate;
}
}
$array[] = $total;
}
return $array;
}
return false;
}
Now what I need to be able to do is grab the values from the array and add them all together. This was my latest attempt. But only the items in the last array get added together.
$weeklyGross = $chart->getChartInfo($conn, $weekly);
if(!empty($weeklyGross)){
foreach($weeklyGross as $row){
$hours = $row['total_hours'];
$totalItems = $row['requested_items'];
$delivery_cost = $row['delivery_cost'];
//Store total items in array
$items = explode(',', $totalItems);
$item_name = array();
$totalPrice = 0;
foreach ($items as $var){
//Get items from price total function
$addItems = $chart->priceTotal($conn, $var, $hours);
//$completeOrder = array_merge($addItems);
print_r($addItems);
foreach($addItems as $k){
$totalPrice += $k;
}
}
$totalPrice += $delivery_cost;
}
print_r($totalPrice);
}
Here is the printout of the arrays, and the values that I would like to add all together.
Array (
[0] => 420
[1] => 200
)
Array (
[0] => 270
)
Array (
[0] => 350
[1] => 350
)
Array (
[0] => 270
)
Array (
[0] => 220
)
Array (
[0] => 280
)
Array (
[0] => 270
[1] => 300
)
Array (
[0] => 700
[1] => 380
)
See what I have done with $totalPrice
$weeklyGross = $chart->getChartInfo($conn, $weekly);
if(!empty($weeklyGross)){
$totalPrice = 0; // << Put this here
foreach($weeklyGross as $row){
$hours = $row['total_hours'];
$totalItems = $row['requested_items'];
$delivery_cost = $row['delivery_cost'];
//Store total items in array
$items = explode(',', $totalItems);
$item_name = array();
/// $totalPrice = 0; // << not here, as it resets the total price on each loop
foreach ($items as $var){
//Get items from price total function
$addItems = $chart->priceTotal($conn, $var, $hours);
//$completeOrder = array_merge($addItems);
print_r($addItems);
foreach($addItems as $k){
$totalPrice += $k;
}
}
$totalPrice += $delivery_cost;
}
print_r($totalPrice);
}
$data1 = array();
$final_ttt = "15";
$items = [];
for ($j = 1; $j <= $final_ttt; ++$j)
{
$TeamNo = "t$j";
$items[] = $TeamNo;
}
print_r($items);
In while loop im getting below values
$day = 1;
$i = 0;
while($row = $qry->fetch())
{
$name = $row['name']; //a,b,c,d
$loopvalue = $row['loopvalue']; // getting 2,3,8,3,4
$data1[]=array("name" => $name,"loopvalue" => $loopvalue);
if( $i % $final_ttt == 0 )
{
$fday = "Day ".$day;
$day++;
}
}
output
name value Team day
a 2 t1,t12 1
b 3 t3,t4,t5 1
c 8 t5,t6,t7,t8,t9,t10,t11,t12 1
d 3 t13,t14,t15 1
e 4 t1,t2,t3,t4 2
How to allocate the teams to based on while loop value. if i get value is 2 => then i need to allocate first 2 teams t1,t2 like this. kinldy help me.
Thanks you in advance
--- We are editing the question as the solution provided does not work in certain test cases. Like the one shown in the attached image.
Here is the updated code for above image output
$lastIndex = 0;
$day = 1;
while($row = $qry->fetch())
{
$name = $row['name']; //a,b,c,d
$loopvalue = $row['loopvalue']; // getting 2,3,8,3,4
if($i==0)
{
$fday = "Day ".$day;//Day 1 for first Itration
$day = 2;
}
$team = implode(',',array_slice($items, $lastIndex, $loopvalue));
$lastIndex = $lastIndex + $loopvalue;
if($lastIndex > count($items))
{
$lastIndex = $lastIndex - count($items);
$team .= ','.implode(',',array_slice($items, 0, $lastIndex));
$fday = "Day ".$day;
$day++;
}
$data1[]=array("name" => $name,"loopvalue" => $loopvalue, "day" => $fday, 'team' => $team);
$row ++;
}
print_r($data1);
You can try something like below
$lastIndex = 0;
while($row = $qry->fetch())
{
$name = $row['name']; //a,b,c,d
$loopvalue = $row['loopvalue']; // getting 2,3,8,3,4
$team = implode(',',array_slice($items, $lastIndex, $loopvalue));
$lastIndex = $lastIndex + $loopvalue;
if($lastIndex > count($items)) {
$lastIndex = $lastIndex - count($items);
$team .= ','.implode(',',array_slice($items, 0, $lastIndex));
}
$data1[]=array("name" => $name,"loopvalue" => $loopvalue, 'team' => $team);
$row ++;
}
print_r($data1);
Will result like
Array ( [0] => Array ( [name] => a [loopvalue] => 2 [team] => t1,t2 ) [1] => Array ( [name] => b [loopvalue] => 3 [team] => t3,t4,t5 ) [2] => Array ( [name] => c [loopvalue] => 8 [team] => t6,t7,t8,t9,t10,t11,t12,t13 ) [3] => Array ( [name] => d [loopvalue] => 3 [team] => t14,t15,t1 ) [4] => Array ( [name] => e [loopvalue] => 4 [team] => t2,t3,t4,t5 ) )
Let me know if this solve your problem.
I'm trying to create foreach statement using multidimensional array.
Controller:
function index()
{
$index1 = 0;
$index2 = 0;
$index3 = 0;
$index4 = 0;
$result1 = $this->data->get_test('kdprogram','kdprogram');
foreach($result1 as $row1){
$array_temp[$index1] = $row1;
$result2 = $this->data->get_test('kdgiat','kdgiat','kdprogram = '.$row1['kdprogram']);
foreach($result2 as $row2){
$array_temp[$index1][$index2] = $row2;
$result3 = $this->data->get_test('kdoutput','kdoutput','kdprogram = '.$row1['kdprogram'].' and kdgiat = '.$row2['kdgiat']);
foreach($result3 as $row3){
$array_temp[$index1][$index2][$index3] = $row3;
$result4 = $this->data->get_test('kdsoutput','kdsoutput','kdprogram = '.$row1['kdprogram'].' and kdgiat = '.$row2['kdgiat'] .' and kdoutput = '.$row3['kdoutput']);
foreach($result4 as $row4){
$array_temp[$index1][$index2][$index3][$index4] = $row4;
$index4++;
}
$index3 ++;
}
$index2 ++;
}
$index1 ++;
}
//print_r($array_temp);
$data['damn'] = $array_temp;
$this->load->view('report/laporan_output', $data);
}
$data contains:
Array
(
[0] => Array
(
[kdprogram] => 06
[0] => Array
(
[kdgiat] => 3400
[0] => Array
(
[kdoutput] => 001
[0] => Array
(
[kdsoutput] => 001
)
[1] => Array
(
[kdsoutput] => 006
)
)
[1] => Array
(
[kdoutput] => 008
[2] => Array
(
[kdsoutput] => 001
)
)
)
)
)
How to echo each array (kdprogram, kdgiat, etc) on view especially with html table?
Am i doing it right?
Thanks
it looks kinda ugly and i would use some sort of recursive function but here is your way
in controller ( i assume the arrays have numeric index otherwise you have to use some sort of counter like you did in your code )
foreach($result1 as $a_counter=>$row1)
{
$array_temp[$a_counter] = array( 'parent'=>$row1 , 'child'=>array());
$result2 = $this->data->get_test('kdgiat','kdgiat','kdprogram = '.$row1['kdprogram']);
foreach($result2 as $b_counter=> $row2)
{
$array_temp[$a_counter]['child'][$b_counter] = array( 'parent'=>$row2 , 'child'=>array());
$result3 = $this->data->get_test('kdoutput','kdoutput','kdprogram = '.$row1['kdprogram'].' and kdgiat = '.$row2['kdgiat']);
foreach($result3 as $c_counter=>$row3)
{
$array_temp[$a_counter]['child'][$b_counter]['child'][$c_counter] = array( 'parent'=>$row3 , 'child'=>array());
$result4 = $this->data->get_test('kdsoutput','kdsoutput','kdprogram = '.$row1['kdprogram'].' and kdgiat = '.$row2['kdgiat'] .' and kdoutput = '.$row3['kdoutput']);
foreach($result4 as $row4)
{
$array_temp[$a_counter]['child'][$b_counter]['child'][$c_counter]['child'][] = $row;
}
}
}
}
in the view
foreach($result as $a )
{
// show a
foreach($a['child'] as $b )
{
// show b
foreach($b['child'] as $c )
{
// show c
foreach($c['child'] as $d )
{
// show d
}
}
}
}
I have an array with arrays in it:
Array (
[0] => Array (
[qty] => 2
[name] => thing 1
[model] => 70001
[price] => 129.00
[weight] => 75.00
[id] => 139
)
[1] => Array (
[qty] => 1
[name] => thing 2
[model] => 70002
[price] => 199.00
[weight] => 45.00
[id] => 53
)
)
I need to pull the weight of each product compare it to a MySQL DB (I can do this) multiply that by the qty and return a cost; then do the same to the next and so on.
Final Update (with complete class function):
function quote($method = '') {
global $order, $cart, $shipping_weight, $shipping_num_boxes;
$order->delivery['postcode'] = strtoupper($order->delivery['postcode']);
$order->delivery['postcode'] = str_replace (' ', '', $order->delivery['postcode']);
foreach($order->products as $value){//loop through arrays within arrays
$weight = $value['weight'];
$qty = $value['qty'];
$id = $value['id'];
if($weight <= 25)//find rate
$weight_class = 'w25';
elseif(25 < $weight && $weight <= 50)
$weight_class = 'w50';
elseif(50 < $weight && $weight <= 100)
$weight_class = 'w100';
elseif(100 < $weight && $weight <= 150)
$weight_class = 'w150';
else
$weight_class = 'w300';
//strip postal code to fsa
$postalcode = strtoupper(substr($order->delivery['postcode'],0,3));
//query database for cost
$postal_query = 'SELECT ' . $weight_class . ' FROM postal_codes WHERE fsa = "' . $postalcode . '"';
$result = mysql_query($postal_query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$rate = $row[$weight_class].'<br>';
}
$cost = $rate * $qty;//multiple by number of products
$shipping_total[$id] = $cost;//add total cost for this product(s) to array
}
$shipping_rate = array_sum($shipping_total);//sum array to total(s)
$this->quotes = array( 'id' => $this->code,
'module' => MODULE_SHIPPING_DLY3_TEXT_TITLE,
'methods' => array(array( 'id' => $this->code,
'title' => MODULE_SHIPPING_DLY3_TEXT_WAY,
'cost' => $shipping_rate)));
if (tep_not_null($this->icon)) $this->quotes['icon'] = tep_image($this->icon, $this->title);
if ($this->tax_class > 0) {
$this->quotes['tax'] = tep_get_tax_rate($this->tax_class, $order->delivery['country']['id'], $order->delivery['zone_id']);
}
return $this->quotes;
}
I'll update if i figure out a way to reduce the number of queries..
Jesse
//Go over all products
foreach($array as $value){
$weight = $value['weight'];
// query goes here
}
I feel like I'm not understanding what you're asking but why not try
foreach($items as $id => $item)
{
$cost = $item['weight'] * $item['qty'];
}
I have an array that will be display with pagination.
Array
(
[0] => Array
(
[0] => 1.00
[1] => 25.99
[2] => 5685.24
[3] => 568.36
)
[1] => Array
(
[0] => 1.00
[1] => 25.99
[2] => 5685.24
[3] => 568.36
)
[2] => Array
(
[0] => 1.00
[1] => 25.99
)
[3] => Array
(
[0] => 1.00
[1] => 25.99
)
)
for example:
If $show_per_page = 2 =>$nb_page = ceil(12 / 2 ) = 6
12 is the number of orders in array.
Html(table) output will look like this
firstpage
1.00
25.99
next page
5685.24
568.36
Total = 6 280,59
next page
1.00
25.99
next page
... etc ...
Anyboday Know to do this manipulate?
My Idea is to create a function ( I AM TRYING)
$show_per_page = 2;
function paganation($base_arr,$page=1){
GLOBAL $show_per_page;
foreach($base_arr as $idx=>$order){
$total = 0;
for ($i=0;$i<$show_per_page;$i++ ){
$total += $order[$i];
echo $order[$i]."<p>";
}
echo "==============<p>";
echo "TOTAL: ".$total."<p>";
echo "==============<p>";
}
}
paganation($base_arr,1);
Here is simple class to achieve your pagination.
class MyPaginator
{
protected $_array = null;
protected $_count = 0;
protected $show_per_page = 2;
public function __construct(array $array)
{
$this->setupItems($array);
}
private function setupItems(array $items)
{
foreach ($items as $key => $item) {
if (is_array($item)) {
$this->setupItems($item);
} else {
$this->_count++;
$this->_array[] = $item;
}
}
}
public function paganation($page=1)
{
$nextMaxItem = $this->show_per_page * $page;
$fromItem = ($page - 1) * $this->show_per_page;
$maxPages = (int) $this->_count / $this->show_per_page;
$total = 0;
for ($i = $fromItem; $i < $nextMaxItem; $i++) {
echo $this->_array[$i] . '<br />';
$total += $this->_array[$i];
}
echo "==============<p>";
echo "TOTAL: " . $total . "<p>";
echo "==============<p>";
$previous = $page - 1;
if ($page > 1) {
echo '<<';
}
$next = $page + 1;
if ($next <= $maxPages) {
echo '>>';
}
}
}
$array = array(
array(
1.00, 25.99, 5685.24, 568.36
),
array(
1.00, 25.99, 5685.24, 568.36
), array(
1.00, 25.99
), array(
1.00, 25.99
),
);
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$pag = new MyPaginator($array);
$pag->paganation($page);