Adding multi dimensional array to database in PHP - php

Array ( [0] => Array ( [0] => Array ( [name] => Heart Choclates [code] => LFB-P-10 [qty] => 1 [type] => main [price] => 1200 [stock] => 5 [image] => choclates-valentines-day.jpg [quantity] => 12 [expdate] => May 27th 2017 [exptime] => 11:00 PM to 12:00 AM [expdtype] => Mid night delivery ) [1] => Array ( [name] => Birthday Pink [code] => KB-P-5 [qty] => 1 [type] => addon [price] => 600 [stock] => 7 [image] => pink-roses.jpg [expdate] => May 27th 2017 [exptime] => 11:00 PM to 12:00 AM [expdtype] => Mid night delivery ) ) [1] => Array ( [0] => Array ( [name] => Red & Yellow Roses [code] => KB-P-6 [qty] => 1 [type] => main [price] => 800 [stock] => 9 [image] => birthday-red-roses.jpg [expdate] => May 27th 2017 [exptime] => 11:00 PM to 12:00 AM [expdtype] => Mid night delivery ) [1] => Array ( [name] => Signature Cake [code] => KB-P-7 [qty] => 1 [type] => addon [price] => 0 [stock] => 9 [image] => signature-cake.jpg [expdate] => May 27th 2017 [exptime] => 11:00 PM to 12:00 AM [expdtype] => Mid night delivery ) [2] => Array ( [name] => Truffle Cake [code] => KB-P-8 [qty] => 1 [type] => addon [price] => 10 [stock] => 7 [image] => truffle-cake.jpg [expdate] => May 27th 2017 [exptime] => 11:00 PM to 12:00 AM [expdtype] => Mid night delivery ) ) )
I have an array like this.. an array of orders and array of products inside each array of orders. Now i need to add these arrays into database with orders in each row and products seprated by a <br/> . How is it possible? Thanks in advance.
I used this for each to print the code.
<?php
session_start();
error_reporting(0);
print_r($_SESSION["products"]);
foreach($_SESSION["products"] as $row => $temp){
?>
<div>
<?php
foreach($temp as $innerRow => $cart_itm){
?>
<div><?php echo $cart_itm['code']; ?></div>
<?php
}
?>
</div>
<?php
}
?>
Expecting this Result

Try this sample code.
$orderList[1001] = array(
0 => array(
'name' => 'Heart Choclates',
'code' => 'LFB-P-10',
'qty' => 1,
'type' => 'main',
'price' => 1200,
'stock' => 5,
'image' => 'choclates-valentines-day.jpg',
'quantity' => 12,
'expdate' => 'May 27th 2017',
'exptime' => '11:00 PM to 12:00 AM',
'expdtype' => 'Mid night delivery'
),
1 => array(
'name' => 'Birthday Pink',
'code' => 'KB-P-5',
'qty' => 1,
'type' => 'addon',
'price' => 600,
'stock' => 7,
'image' => 'pink-roses.jpg',
'quantity' => 3,
'expdate' => 'May 27th 2017',
'exptime' => '11:00 PM to 12:00 AM',
'expdtype' => 'Mid night delivery'
)
);
$orderList[1002] = array(
0 => array(
'name' => 'Red & Yellow Roses',
'code' => 'KB-P-6',
'qty' => 1,
'type' => 'main',
'price' => 800,
'stock' => 9,
'image' => 'birthday-red-roses.jpg',
'quantity' => 10,
'expdate' => 'May 27th 2017',
'exptime' => '11:00 PM to 12:00 AM',
'expdtype' => 'Mid night delivery'
)
);
echo '<pre>';
print_r($orderList);
echo '<pre>';
$productList = array();
foreach ($orderList as $key => $value)
{
$names = array();
$quantity = array();
foreach ($value as $key1 => $value1)
{
$names[] = $value1['name'];
$quantity[] = $value1['quantity'];
}
$productList[$key]['names'] = implode('<br>', $names); // Used `:` insted of '<br>' for separator. But, You can use whatever you want. But, better don't use any HTML tag.
$productList[$key]['quantity'] = implode('<br>', $quantity);
}
echo '<pre>';
print_r($productList);
echo '<pre>';
// Sample DATA INSERTION Query by PDO
try {
$conn = new PDO('mysql:host=localhost;dbproductName=someDatabase', $userproductName, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Prepare the query ONCE
$stmt = $conn->prepare('INSERT INTO someTable VALUES(:name, :quantity)');
foreach ($productList as $key => $value) {
$productName = $value['names'];
$productQuantity = $value['quantity'];
$stmt->bindParam(':name', $productName);
$stmt->bindParam(':quantity', $productQuantity);
$stmt->execute();
}
} catch(PDOException $e) {
echo $e->getMessage();
}
// Ref : https://code.tutsplus.com/tutorials/php-database-access-are-you-doing-it-correctly--net-25338

I hope this will get you started:
$data = array(
array(
array(
'name' => 'Heart Choclates',
'code' => 'LFB-P-10',
'qty' => '1'
),
array(
'name' => 'Birthday Pink',
'code' => 'KB-P-5',
'qty' => '1'
)
),
array(
array(
'name' => 'Red & Yellow Roses',
'code' => 'KB-P-6',
'qty' => '1'
),
array(
'name' => 'Signature Cake',
'code' => 'KB-P-7',
'qty' => '1'
),
array(
'name' => 'Truffle Cake',
'code' => 'KB-P-8',
'qty' => '1'
)
)
);
foreach( $data as $row_item )
{
$row = array();
foreach( $row_item as $product )
{
foreach( $product as $key => $value )
{
if( isset( $row[ $key ] ) )
$row[ $key ] .= $value . ' <br> ';
else
$row[ $key ] = $value . ' <br> ';
}
}
//---
echo 'Row: <br>';
var_dump( $row );
echo '<br><br>';
//-- insert the contents of $row array into the database
}
Output:
You can insert the contents of $row array into database.
EDIT
Please note that, the above answer is based on your specific question that you asked.
I still didn't understood what exactly you are doing here. If you are trying to store the details of an order, then this is a poor method of accomplishing it! You should keep separate database table and use a relationship to join together. This is what a relational database is for!
For example, let the two tables be tblOrderMaster and tblOrderDetails.
Here, in the tblOrderMaster table, the primary key will be the order_id and you would probably gonna store the total amount, discount amount, total service tax, order date, customer id, order status, etc.
And in the tblOrderDetails table, you are gonna have several rows, in which we are gonna store each products of a particular order. For example, it will store order id (foreign key), product id, unit price, quantity, tax, total (unit_price x quantity), etc..
This would be the proper way, I believe.

Related

sum value in foreach loop based on another value php

I have an array like below. There are id, label, cost, and cid in an array. We want to sum the cost based on the cid like for cid 22 cost should be 196.5 and for cid 11 cost should be 44.4. In our out put array we want to keep the label, cost (sum), and cid, Please see expected output array.
Array
(
[0] => Array
(
[id] => 1331
[label] => PM1
[cost] => 98.25
[cid] => 22
[product_id] => 133
)
[1] => Array
(
[id] => 1332
[label] => PM3
[cost] => 22.20
[cid] => 11
[product_id] => 133
)
[2] => Array
(
[id] => 1341
[label] => PM1
[cost] => 98.25
[cid] => 22
[product_id] => 134
)
[3] => Array
(
[id] => 1342
[label] => PM3
[cost] => 22.20
[cid] => 11
[product_id] => 134
)
)
Tried below
foreach ($array $key => $value) {
$final[$value['cid']] += $value['cost'];
}
print_r ($final);
Getting below as an output
Array
(
[22] => 196.5
[11] => 44.4
)
Want expected output like below.
Array
(
[22] => Array
(
[label] => PM1
[cost] => 196.5
[cid] => 22
)
[11] => Array
(
[label] => PM3
[cost] => 44.4
[cid] => 11
)
)
Basically want to sum cost based on cid and want to keep the label, cost (sum), and cid.
Any help will be greatly appreciated.
I believe this should do the trick
$CIDs_identified = array();
$final_array = array();
foreach($original_array as $small_array){
if(!in_array($small_array['cid'], $CIDs_identified)){
$CIDs_identified[] = $small_array['cid'];
$final_array[$small_array['cid']] = array(
'label' => $small_array['label'],
'cost' => $small_array['cost'],
'cid' => $small_array['cid'],
);
}else{
$final_array[$small_array['cid']]['cost'] += $small_array['cost'];
}
}
On this site, if you can provide your source array in usable format, that is really helpful so that we don't have to retype it. One way to do that is using var_export.
Below is a simple version. Create an array indexed by cid. If that item doesn't exist, populate it with the basic data and a zero cost. Then on each loop, including the initial, add the row's cost.
<?php
$data = [
[
'id' => 1331,
'label' => 'PMI',
'cost' => 98.25,
'cid' => 22,
'product_id' => 133,
],
[
'id' => 1341,
'label' => 'PMI',
'cost' => 98.25,
'cid' => 22,
'product_id' => 134,
],
];
$output = [];
foreach ($data as $item) {
if (!isset($output[$item['cid']])) {
$output[$item['cid']] = [
'label' => $item['label'],
'cost' => 0,
'cid' => $item['cid'],
];
}
$output[$item['cid']]['cost'] += $item['cost'];
}
print_r($output);
Demo here: https://3v4l.org/MY6Xu
$list = [
[ 'id' => 1331, 'label' => 'PM1', 'cost' => 98.25, 'cid' => 22, 'product_id' => 133 ],
[ 'id' => 1332, 'label' => 'PM3', 'cost' => 22.20, 'cid' => 11, 'product_id' => 133 ],
[ 'id' => 1341, 'label' => 'PM1', 'cost' => 98.25, 'cid' => 22, 'product_id' => 134 ],
[ 'id' => 1342, 'label' => 'PM3', 'cost' => 22.20, 'cid' => 11, 'product_id' => 134 ]
];
$result = [];
array_walk($list, function ($item) use (&$result) {
if (isset($result[$item['cid']])) {
$result[$item['cid']]['cost'] = $item['cost'] + $result[$item['cid']]['cost'];
} else {
$result[$item['cid']] = [ 'label' => $item['label'], 'cost' => $item['cost'], 'cid' => $item['cid'] ];
}
});
print_r($result);
Output:
Array
(
[22] => Array
(
[label] => PM1
[cost] => 196.5
[cid] => 22
)
[11] => Array
(
[label] => PM3
[cost] => 44.4
[cid] => 11
)
)

PHP Forming Custom Array from Array within array

I'm having an array of three months which has Three Months Data and it holds Savings & Discount Information something like the below:
graphData holds the DataArr.
[DataArr] => Array
[0] => Array
(
[data] => Array
(
[0] => Array
(
[Month] => 10 Jan 2019
[Cost] => 60.3
[Name] => Savings
)
[1] => Array
(
[Month] => 10 Feb 2019
[Cost] => 45.3
[Name] => Savings
)
[2] => Array
(
[Month] => 10 Mar 2019
[Cost] => 50.6
[Name] => Savings
)
)
)
[1] => Array
(
[data] => Array
(
[0] => Array
(
[Month] => 10 Jan 2019
[Cost] => 89.62
[Name] => Discount
)
[1] => Array
(
[Month] => 10 Feb 2019
[Cost] => 20.2
[Name] => Discount
)
[2] => Array
(
[Month] => 10 Mar 2019
[Cost] => 0.0
[Name] => Discount
)
)
)
REQUIRED ARRAY - To Pass into Morris.js Line Chart
Now I want to iterate into this array and want to have the array format in a way as below
[data] => Array
(
[0] => Array
(
[Month] => 10 Jan 2019
[Savings] => 60.3
[Discount] => 89.62
)
[1] => Array
(
[Month] => 10 Feb 2019
[Saving] => 45.3
[Discount] => 20.2
)
[2] => Array
(
[Month] => 10 Mar 2019
[Saving] => 50.6
[Discount] => 0.0
)
)
Can you please share me how I can go about getting this into the required array using PHP? I tried array_push and other methods with JQuery Array methods as well, but all my efforts failed, and I'm working on this from past 3 days, any help is greatly appreciated.
Even tried with PHP foreach but even that failed, missing something and have no more ideas on how to get this working! Please let me know if any of you have much ideas on this.
Thanks
EDIT
**SAMPLE CODE I TRIED IN PHP **
for($k = 0; $k < sizeof($graphData['DataArr']); $k++ ) {
for($l = 0; $l < sizeof($graphData['DataArr'][$k]); $l++ ) {
array_push($graphData['DataArr'], array(
'label' => $graphData['DataArr'][$k][$l]['label'],
'percent' => $graphData['DataArr'][$k][$l]['percentage']
)
);
}
}
Here label => COST, DISCOUNT and Percentage is the value associated with the labels.
<?php
$graphData =
array(
'DataArr' =>
array
(
array(
'data' => array
(
array
(
'Month' => '10 Jan 2019',
'Cost' => 60.3,
'Name' => 'Savings'
),
array
(
'Month' => '10 Feb 2019',
'Cost' => 45.3,
'Name' => 'Savings'
),
array
(
'Month' => '10 Mar 2019',
'Cost' => 50.6,
'Name' => 'Savings'
)
)
),
array
(
'data' => array
(
array
(
'Month' => '10 Jan 2019',
'Cost' => 89.62,
'Name' => 'Discount'
),
array
(
'Month' => '10 Feb 2019',
'Cost' => 20.2,
'Name' => 'Discount'
),
array
(
'Month' => '10 Mar 2019',
'Cost' => 0.0,
'Name' => 'Discount'
)
)
)
)
);
$result = [];
foreach($graphData['DataArr'] as $value){
foreach($value['data'] as $details){
if(!isset($result['data'][$details['Month']])) $result['data'][$details['Month']] = ['Month' => $details['Month']];
$result['data'][$details['Month']][$details['Name']] = $details['Cost'];
}
}
$result['data'] = array_values($result['data']); // to eliminate keys
print_r($result);
Demo: https://3v4l.org/QMVuR
We first create a $result array with data key in it.
We loop over $graphData and store the values of Month,Savings and Discount under the indexed key value of Month.
In the end, we do array_values() to remove the keys.
Based on what you provided here is the code need to produce the new Array:
<?php
$data = [
[
'data' => [
[
'Month' => '10 Jan 2019',
'Cost' => 60.3,
'Name' => 'Savings'
],
[
'Month' => '10 Feb 2019',
'Cost' => 45.3,
'Name' => 'Savings'
],
[
'Month' => '10 Mar 2019',
'Cost' => 50.6,
'Name' => 'Savings'
]
],
],
[
'data' => [
[
'Month' => '10 Jan 2019',
'Cost' => 89.62,
'Name' => 'Discount'
],
[
'Month' => '10 Feb 2019',
'Cost' => 20.2,
'Name' => 'Discount'
],
[
'Month' => '10 Mar 2019',
'Cost' => 0.0,
'Name' => 'Discount'
]
],
]
];
$new_arr = ['data' => []];
echo "<pre>";
foreach( $data[0]['data'] as $key => $value) {
// $new_arr['data'][$k]['Month'] =
$new_arr['data'][$key]['Month'] = $value['Month'];
$new_arr['data'][$key]['Discount'] = $value['Cost'];
$new_arr['data'][$key]['Savings'] = $data[1]['data'][$key]['Cost'];
}
print_r($new_arr);
Note: this code assumes that $data array will only have 2 main elements, more elements in this array might might cause different behaviour.

Php check and replace if value exist in multi array?

Problem:
I dont know/understand how to check if date and place exists on the same "row" and they exists more then once.
Second, how do i then merge an array
my case MergeArray with ArraySchedule
Code:
$ArraySchedule = array();
while ($data = $stmt -> fetch(PDO::FETCH_ASSOC)) {
$schedules = array(
"id" => $data['id'],
"name" => $data['name'],
"date" => $data['date'],
"time" => $data['time'],
"place_id" => $data['place_id'],
"place" => $data['place'],
);
array_push($ArraySchedule, $schedules);
}
$dupe_array = array();
foreach ($ArraySchedule as $key => $value) {
if(++$dupe_array[$value["date"]] > 1 && ++$dupe_array[$value["place_id"]] > 1 ){
// this statement is wrong, i want something like:
// if date and place_id exists on the same "row" and they exists more then once
}
}
What i want to do:
Check if ArraySchedule contains schedules that have the same date and place,
if there is more than one schedule that has the same date and place_id.
then I want to update ArraySchedule with this structure
$MergeArray = array(
"id" => ArraySchedule['id'],
"name" => array(
"name" => scheduleSameDateAndPlace['name'],
"name" => scheduleSameDateAndPlace['name'],
"name" => scheduleSameDateAndPlace['name'],
),
"date" => $ArraySchedule['date'],
"time" => $ArraySchedule['time'],
"place_id" => $ArraySchedule['place_id'],
"place_name" => $ArraySchedule['place_name'],
),
MergeArray with ArraySchedule?
anyway...
Output I think I want?
Print_r($ArraySchedule)
array(
[0] =>
array(
[id] => 1
[names] => Simon
[date] => 2019-01-02
[time] 18.00
[place_id] => Tystberga Park
[place] => Tystberga
)
[1] =>
array(
[id] => 2
//[names] insted of [name]?
[names] =>
array(
[name] => Vincent
[name] => Angel
[name] => Kim
)
[date] => 2019-02-17
[time] => 13.00
[place_id] => Borås Park
[place] => Borås
)
[2] =>
array(
[id] => 3
// [names] is always an array?
[names] => Caitlyn
[date] => 2019-03-15
[time] 13.00
[place_id] => Plaza Park
[place] => EvPark
)
)
You can use array-reduce. Consider the following:
function mergeByDateAndPlace($carry, $item) {
$key = $item["place_id"] . $item["date"]; // creating key matching exact place and date
if (!isset($carry[$key])) {
$carry[$key]["name"] = $item["name"];
} else {
$carry[$key] = $item;
$item["name"] = [$item["name"]]; // make default array with 1 element so later can be append other names
}
return $carry;
}
Now use it with:
$MergeArray = array_reduce($ArraySchedule, "mergeByDateAndPlace", []);
If you later want to know if there were any duplicate you can just loop on $MergeArray. You can also use array_values if you want to discard the concat keys.
Notice #Nick 2 important comment about saving the first loop and the "time" value that need to be decided. Also notice your desire output contain multi element with the same key ("name") - you need to append them with int key - Array can not have duplicate keys.
Hope that helps!
Here is my data from my database:
var_export($ArraySchedule)
array (
0 => array ( 'id' => '225', 'place_id' => 'Alviks Kulturhus', 'name' => 'BarraBazz', 'date' => '2019-03-19', 'placeadress' => 'Gustavslundsvägen 1', ),
1 => array ( 'id' => '229', 'place_id' => 'Axelhuset Göteborg', 'name' => 'Anders Björk', 'date' => '2019-04-08', 'placeadress' => 'Axel Dahlströms torg 3', ),
2 => array ( 'id' => '230', 'place_id' => 'Axelhuset Göteborg', 'name' => 'Black Jack', 'date' => '2019-04-08', 'placeadress' => 'Axel Dahlströms torg 3', ),
3 => array ( 'id' => '227', 'place_id' => 'Arosdansen Syrianska Kulturcentret', 'name' => 'BarraBazz', 'date' => '2019-05-08', 'placeadress' => 'Narvavägen 90', ),
4 => array ( 'id' => '228', 'place_id' => 'Aspåsnäset', 'name' => 'Blender', 'date' => '2019-05-25', 'placeadress' => 'Aspåsnäset 167', ),
5 => array ( 'id' => '226', 'place_id' => 'Arenan Västervik Resort', 'name' => 'Blender', 'date' => '2019-06-29', 'placeadress' => 'Lysingsvägen', ),
6 => array ( 'id' => '222', 'place_id' => 'Alingsåsparken', 'name' => 'Bendéns', 'date' => '2019-07-16', 'placeadress' => 'Folkparksgatan 3A', ),
7 => array ( 'id' => '223', 'place_id' => 'Alingsåsparken', 'name' => 'Charlies', 'date' => '2019-07-16', 'placeadress' => 'Folkparksgatan 3A', ),
8 => array ( 'id' => '224', 'place_id' => 'Allhuset Södertälje', 'name' => 'Cedrix', 'date' => '2019-07-16', 'placeadress' => 'Barrtorpsvägen 1A', ), )
I want to update the "name" with an array of names everytime that place_id and date are the same.
This is the output I want:
Array (
[0] =>
Array ( [id] => 225 [place_id] => Alviks Kulturhus [name] => BarraBazz [date] => 2019-03-19 [placeadress] => Gustavslundsvägen 1 )
[1] =>
Array ( [id] => 229 [place_id] => Axelhuset Göteborg [name] => Array([0] => Anders Björk [1] => Black Jack ) [date] => 2019-04-08 [placeadress] => Axel Dahlströms torg 3 )
[3] =>
Array ( [id] => 227 [place_id] => Arosdansen Syrianska Kulturcentret [name] => BarraBazz [date] => 2019-05-08 [placeadress] => Narvavägen 90 )
[4] =>
Array ( [id] => 228 [place_id] => Aspåsnäset [name] => Blender [date] => 2019-05-25 [placeadress] => Aspåsnäset 167 )
[5] =>
Array ( [id] => 226 [place_id] => Arenan Västervik Resort [name] => Blender [date] => 2019-06-29 [placeadress] => Lysingsvägen )
[6] =>
Array ( [id] => 222 [place_id] => [Alingsåsparken] [name] => Array([0] => Bendéns [1] => Charlies) [date] => 2019-07-16 [placeadress] => Folkparksgatan 3A )
[8] =>
Array ( [id] => 224 [place_id] => Allhuset Södertälje [name] => Cedrix [date] => 2019-07-16 [placeadress] => Barrtorpsvägen 1A ) )
Here is my updated code
$sql = "SELECT `schedule`.`id`,`schedule`.`place_id`,`schedule`.`name`,`schedule`.`date`,`places`.`placeadress` FROM `schedule` INNER JOIN `places` ON `schedule`.`place_id`=`places`.`place_id` ORDER BY `date`";
$stmt = $db -> prepare($sql);
$stmt -> execute();
$ArraySchedule = $stmt->fetchAll(PDO::FETCH_ASSOC);
var_export($ArraySchedule);
$DatePlace = array();
foreach ($ArraySchedule as $key => $Schedule){
$Arrayquery = "SELECT `schedule`.`id`,`schedule`.`place_id`,`schedule`.`name`,`schedule`.`date`,`places`.`placeadress` FROM `schedule` INNER JOIN `places` ON `schedule`.`place_id`=`places`.`place_id` WHERE `schedule`.`date`= :date_ AND `schedule`.`place_id` = :place_id ORDER BY `date`";
$ArrayStmt = $db->prepare($Arrayquery);
$ArrayStmt -> execute(array(":date_" => $Schedule['date'],":place_id" => $Schedule['place_id']));
//Getting every $Schedule that has the same date and place_id
if($ArrayStmt->rowCount() > 1){
//Here i want two update the name inside
//$ArrayArraySchedule with an array of names
//that has the same place and date?
}
}
print_r($ArraySchedule);

Print associative array to table

I have an associative array like this, i want to generate a table with these data, like breakfast, snacks, lunch, supper, dinner in row the following is the code I've tried, but I am stuck where to break the table row because when the array contains more than one item.i wants to Print associative array to table
*--------------------------------------------------*
| **Breakfast Snacks Lunch Supper Dinner** |
| test test test testfrom
|testfrom
*--------------------------------------------------*
array output is as follow
Array
(
[meal_plan_id] => 17
[calorie_limit] => 1
[total_calorie] => 0
[date] => 2017-12-29
[meal_plan] => Array
(
[0] => Array
(
[meal_type] => bf
[label] => Breakfast
[calorie_limit] => 30
[total_calorie] => 0
[data] => Array
(
[0] => Array
(
[id] => 107
[label] => test
[quantity] => 10
[unit] => g
[status] => bf
)
[1] => Array
(
[id] => 109
[label] => testfrom
[quantity] => 12
[unit] => g
)
)
)
[1] => Array
(
[meal_type] => sn
[label] => Snacks
[calorie_limit] => 10
[total_calorie] => 0
[data] => Array
(
[0] => Array
(
[id] => 108
[label] => test
[quantity] => 121
[unit] => g
)
)
)
[2] => Array
(
[meal_type] => lu
[label] => Lunch
[calorie_limit] => 20
[total_calorie] => 0
[data] => Array
(
[0] => Array
(
[status] => su
)
)
)
[3] => Array
(
[meal_type] => su
[label] => Supper
[calorie_limit] => 30
[total_calorie] => 0
[data] => Array
(
[0] => Array
(
[status] => sn
)
[1] => Array
(
[id] => 116
[label] => test
[quantity] => 200
[unit] => oz
)
)
)
[4] => Array
(
[meal_type] => dn
[label] => Dinner
[calorie_limit] => 20
[total_calorie] => 0
[data] => Array
(
[0] => Array
(
[id] => 113
[label] => test500
[quantity] => 20
[unit] => oz
[status] => dn
)
)
)
)
)
below is the code I've tried
// $daily_meals = show_daily_meals() // contains the array
if(!empty($daily_meals['meal_plan'])){
echo '<tr>';
foreach($daily_meals['meal_plan'] as $meal_plan){
foreach ($meal_plan['data'] as $data){
if(!empty($data['id']))
echo '<td class="'.$meal_type.'" data-meals-id="'.$data['id'].'"><span class="left">'.$data['label'].'</span> <span class="right">'.$data['quantity'].' <a class="delete_row"><i class="fa fa-trash" aria-hidden="true"></i></a></span><div class="row_loader"></div></td>';
else echo '<td></td>';
}
$i++;
if($i%5 == 0) echo '</tr>';
}
}
Here is your solution
Input
<?php
$array = array(
array(
'meal_type' => 'bf',
'label' => 'Breakfast',
'calorie_limit' => 30,
'total_calorie' => 0,
'data' => array(
array(
'id' => 107,
'label' => 'test',
'quantity' => 10,
'unit' => 'g',
'status' => 'bf'
),
array(
'id' => 109,
'label' => 'testfrom',
'quantity' => 12,
'unit' => 'g'
)
)
),
array(
'meal_type' => 'sn',
'label' => 'Snacks',
'calorie_limit' => 10,
'total_calorie' => 0,
'data' => array(
array(
'id' => 108,
'label' => 'test',
'quantity' => 121,
'unit' => 'g'
)
)
),
array(
'meal_type' => 'lu',
'label' => 'Lunch',
'calorie_limit' => 20,
'total_calorie' => 0,
'data' => array(array('status' => 'su'))
),
array(
'meal_type' => 'su',
'label' => 'Supper',
'calorie_limit' => 30,
'total_calorie' => 0,
'data' => array(
array('status' => 'sn'),
array(
'id' => 116,
'label' => 'test',
'quantity' => 200,
'unit' => 'oz'
),
)
),
array(
'meal_type' => 'dn',
'label' => 'Dinner',
'calorie_limit' => 20,
'total_calorie' => 0,
'data' => array(
array(
'id' => 113,
'label' => 'test500',
'quantity' => 20,
'unit' => 'oz',
'status' => 'dn'
)
)
)
);
Solution
1st foreach for parent array. Then second for its child..
foreach($array as $r){
$$r['label'] = '<table width="100%">';
foreach($r['data'] as $s){
if(isset($s['label']))$$r['label'] .= '<tr><td align="center">'.$s['label'].'</td></tr>'; // The if condition check weather the label is exist or not if yes then add that in particular label's table
}
$$r['label'] .= '</table>';
}
echo '
<table width="100%" border="1">
<thead>
<tr>
<th>Breakfast</th>
<th>Snacks</th>
<th>Lunch</th>
<th>Supper</th>
<th>Dinner</th>
</tr>
</thead>
Here all labels canverted into variable by $$r['label']. And all have there own table Now we add all these tables into the master table to get the output.
<tbody>
<tr>
<td>'.$Breakfast.'</td>
<td>'.$Snacks.'</td>
<td>'.$Lunch.'</td>
<td>'.$Supper.'</td>
<td>'.$Dinner.'</td>
</tr>
</tbody>
</table>';
//?// echo "<pre>";print_r($array);
?>
Output
Try storing all your column names in an array and create a table with it:
foreach($array as $row) {
$column[$i]['label'] = $row['label'];
$column[$i]['data'] = $this->getdata($row['data']);
$i++;
}
function getdata($array) {
$data = '';
foreach($array as $row) {
$data. = $row['label'].',';
}
return $data;
}
Create a table with the column names and try inserting data using a loop with respect to insert into

Sum arrays values by week number

Can you sum the below array of sales by weeknumber
Array
(
[0] => Array
(
[DATE] => 2015-03-06
[store] => 18
[weeknum] => 11
[sales] => 10
)
[1] => Array
(
[DATE] => 2015-03-08
[store] => 18
[weeknum] => 11
[sales] => 5
)
[2] => Array
(
[DATE] => 2015-03-09
[store] => 18
[weeknum] => 11
[sales] => 5
)
I would like to achieve something like this
[0] => Array
(
[store] => 18
[weeknum] => 11
[sales] => 20
)
so far i have tried array sum but that doesnt seem to work
There are many different ways and answers (eg.).
For instance:
Using Array Reduce:
$total_sales = array_reduce($items, function($carry, $item){
$carry['store'] = $item['store'];
$carry['weeknum'] = $item['weeknum'];
$carry['sales'] += $item['sales'];
return $carry;
}, []);
Or Using Array column:
$total_sales = array_sum(array_column($items, 'sales'));
Simply iterate through the array and add the field values to a sum container.
I've also added the store number as a unique identifier in case there's multiple stores you want individual info for. If you want it for all stores just change $key = $weekNumber . $item['store']; out with $key = $weekNumber;.
Data:
$items = [
[
'DATE' => '2015-03-06',
'store' => 18,
'weeknum' => 11,
'sales' => 10,
],
[
'DATE' => '2015-03-08',
'store' => 18,
'weeknum' => 11,
'sales' => 5,
],
[
'DATE' => '2015-03-09',
'store' => 18,
'weeknum' => 11,
'sales' => 5,
],
[
'DATE' => '2015-03-09',
'store' => 18,
'weeknum' => 12,
'sales' => 5,
],
];
Code:
<?php
$storeWeekSums = [];
foreach ($items as $item) {
// Save the key to refer to it later
$weekNumber = $item['weeknum'];
$key = $weekNumber . $item['store'];
if (!isset($weekSums[$weekNumber])) {
// The week and store does not already exist, let's create it with a value
$storeWeekSums[$key] = [
'store' => $item['store'],
'weeknum' => $item['weeknum'],
'sales' => $item['sales'],
];
} else {
// The week and store already exists, so we'll add to the current value instead
$storeWeekSums[$key]['sales'] += $item['sales'];
}
}
print_r($storeWeekSums);
Output::
Array
(
[1118] => Array
(
[store] => 18
[weeknum] => 11
[sales] => 5
)
[1218] => Array
(
[store] => 18
[weeknum] => 12
[sales] => 5
)
)
DEMO

Categories