get values from database and sort them based on other fields - php

I'm using php and mysql -[codeigniter framework]- and this is my table structure:
Please visit this image to find out table structure
Every single item is separated to three or four parts that these parts made this item's price.
And these items belong to an invoice that will point using refid. refid is invoice_id in fact.
now I need to get a specific invoice items and show them in a table.
this is what I need:
Please visit this image to find out my need
I do not have any problem to get values from database and I will use codeigniter active records.
As you may know, codeigniter database result_array function will give us an associative array. Now I want to separate every item from other and display them in a html table and I have to use rowspan for every item dependence sub items.
Would you please help me to find out how should I use result array to simply show the result in a html table?

so lets assume that you are getting a result array like this,
$result = array(
array(
'id' => 26,
'price' => 100,
'parent' => 0
),
array(
'id' => 27,
'price' => 100,
'parent' => 26
),
array(
'id' => 28,
'price' => 150,
'parent' => 26
),
array(
'id' => 29,
'price' => 100,
'parent' => 26
),
array(
'id' => 30,
'price' => 100,
'parent' => 0
),
array(
'id' => 31,
'price' => 99,
'parent' => 30
),
array(
'id' => 32,
'price' => 75,
'parent' => 30
),
array(
'id' => 33,
'price' => 600,
'parent' => 0
),
array(
'id' => 34,
'price' => 100,
'parent' => 33
),
array(
'id' => 35,
'price' => 50,
'parent' => 33
),
array(
'id' => 36,
'price' => 100,
'parent' => 33
),
);
i cant insert all the data manually in the array from your image, so i have inserted only the needed once,
so now u can do something like this to group the data of same item,
$new_array = array();
$invoice_price = 0;
foreach ($result as $key => $value) {
$invoice_price += $value['price'];
if($value['parent'] == 0){
$new_array[$value['id']]['other_data'][] = $value;
$new_array[$value['id']]['final_price'] = $value['price'];
}else{
$new_array[$value['parent']]['other_data'][] = $value;
$new_array[$value['parent']]['final_price'] += $value['price'];
}
}
now if u print this $new_array, u will get the following output,
Array
(
[26] => Array
(
[other_data] => Array
(
[0] => Array
(
[id] => 26
[price] => 100
[parent] => 0
)
[1] => Array
(
[id] => 27
[price] => 100
[parent] => 26
)
[2] => Array
(
[id] => 28
[price] => 150
[parent] => 26
)
[3] => Array
(
[id] => 29
[price] => 100
[parent] => 26
)
)
[final_price] => 450
)
[30] => Array
(
[other_data] => Array
(
[0] => Array
(
[id] => 30
[price] => 100
[parent] => 0
)
[1] => Array
(
[id] => 31
[price] => 99
[parent] => 30
)
[2] => Array
(
[id] => 32
[price] => 75
[parent] => 30
)
)
[final_price] => 274
)
[33] => Array
(
[other_data] => Array
(
[0] => Array
(
[id] => 33
[price] => 600
[parent] => 0
)
[1] => Array
(
[id] => 34
[price] => 100
[parent] => 33
)
[2] => Array
(
[id] => 35
[price] => 50
[parent] => 33
)
[3] => Array
(
[id] => 36
[price] => 100
[parent] => 33
)
)
[final_price] => 850
)
)
hope u can see that the data is already groups by items.
now just send the data in your view file,
$this->load->view('yourviewfilename',array('data'=>$new_array,'invoice_price'=>$invoice_price));
and to print the table like your screenshot use the following code,
<table border="1">
<tr>
<th>ID</th>
<th>parent</th>
<th>price</th>
<th>final price</th>
</tr>
<?php $count = 0; ?>
<?php foreach ($data as $key => $value) { ?>
<?php $count++; ?>
<?php foreach ($value['other_data'] as $k => $v) { ?>
<tr>
<?php if ($k == 0) { ?>
<td rowspan="<?php echo count($value['other_data']); ?>"><?php echo $count ?></td>
<?php } ?>
<td> <?php echo $v['parent']; ?></td>
<td> <?php echo $v['price']; ?></td>
<?php if ($k == 0) { ?>
<td rowspan="<?php echo count($value['other_data']); ?>"><?php echo $value['final_price']; ?></td>
<?php } ?>
</tr>
<?php } ?>
<?php } ?>
</table>
u will get output like this,
hope u got the point and can print the other data you needed.

Related

Get total sum of repeating IDs stored in multidimensional array

I have a multidimensional array of items added to cart in codeigniter. Lets say I order food for me and several friends (specific IDs stored in next level array). Now in case someone has more items I need to get total sum of each friend and save it as money owned to me. How to loop all items to get total sum of each friend with same ID (I cannot move the friend ID to parent array). I store them to database in a way we can see in the table below in non-repeating way. I need a new array to get results like this(to store/update them).
friend_id
amount_owned
52
35
28
5
friend_id 0 is me...we skip me != 0
Array
(
[array] => Array
(
[carthashid1] => Array
(
[0] => Array
(
[foodid] => 322
[price] => 5
[name] => Chicken Burger
[options] => Array
(
[friend_id] => 52
[special_instructions] =>
)
[rowid] => ceec8698316fe95ec9d7dccf961f32c1
[num_added] => 5
[sum_price] => 25
)
[1] => Array
(
[foodid] => 323
[price] => 5
[name] => Beef Burger
[options] => Array
(
[friend_id] => 52
[special_instructions] =>
)
[rowid] => c2d1c15d159123d1cbdce967785ef06e
[num_added] => 2
[sum_price] => 10
)
[2] => Array
(
[foodid] => 322
[price] => 5
[name] => Chicken Burger
[options] => Array
(
[friend_id] => 28
[special_instructions] =>
)
[rowid] => 3daa7b14b23a5c0afa9b196ea6e35227
[num_added] => 1
[sum_price] => 5
)
[3] => Array
(
[foodid] => 323
[price] => 5
[name] => Beef Burger
[options] => Array
(
[friend_id] => 0
[special_instructions] =>
)
[rowid] => 734c9cc82cf35e2dcc42f28d96a8ebde
[num_added] => 1
[sum_price] => 5
)
)
)
[finalSum] => 45
[finalItemsCount] => 9
)
It would have taken me less time to check my answer if I didnt have to Hand Code the array, but here it is anyway
$input = [
'array' => [
'carthashid1' => [
[
'foodid' => 322, 'price' => 5,
'name' => 'Chicken Burger',
'options' => ['friend_id' => 52, 'special_instructions' => ''],
'rowid' => 'ceec8698316fe95ec9d7dccf961f32c1', 'num_added' => 5,'sum_price' => 25
],
[
'foodid' => 322, 'price' => 5,
'name' => 'Beef Burger',
'options' => ['friend_id' => 52,'special_instructions' => ''],
'rowid' => 'ceec8698316fe95ec9d7dccf961f32c1', 'num_added' => 2,'sum_price' => 10
],
[
'foodid' => 322,'price' => 5,'name' => 'Chicken Burger',
'options' => ['friend_id' => 28,'special_instructions' => ''],
'rowid' => 'ceec8698316fe95ec9d7dccf961f32c1', 'num_added' => 1,'sum_price' => 5
],
[
'foodid' => 322, 'price' => 5, 'name' => 'Beef Burger',
'options' => ['friend_id' => 0,'special_instructions' => ''],
'rowid' => 'ceec8698316fe95ec9d7dccf961f32c1', 'num_added' => 1, 'sum_price' => 5
]
]
]
];
$friends = [];
foreach($input['array']['carthashid1'] as $ordered){
if ($ordered['options']['friend_id'] == 0) {
// its me, ignore me
continue;
}
if ( ! isset($friends[$ordered['options']['friend_id']]) ) {
// initialise the accumulator for this friend
$friends[$ordered['options']['friend_id']] = 0;
}
$friends[$ordered['options']['friend_id']] += $ordered['sum_price'];
}
print_r($friends);
RESULT
Array
(
[52] => 35
[28] => 5
)
You could theoretically do entire task in single DB query, also the friend_id can be moved to parent array by modifying DB query.
Slightly different approach to keep friend_id, amount_owned structure:
$owned = [];
foreach($arr['array']['carthashid1'] as $item){
if(isset($item['options']['friend_id']) && $item['options']['friend_id'] != 0)
{
if(count($owned) && ($key = array_search($item['options']['friend_id'], array_column($owned, 'friend_id'))) !== false){
// we found friend id in array lets add the price:
$owned[$key]['amount_owned'] += $item['sum_price'];
continue;
}
// when we dont find the friend id in array create that item here:
$owned[] = ['friend_id' => $item['options']['friend_id'], 'amount_owned' => $item['sum_price']];
}
}
print_r($owned);
Result:
Array
(
[0] => Array
(
[friend_id] => 52
[amount_owned] => 35
)
[1] => Array
(
[friend_id] => 28
[amount_owned] => 5
)
)

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

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

PHP Two Arrays Into One Table. First Array Vertical, Second Horizontal

i want result like this in view.
This is (part of) the array:
Array ( [0] => Array ( [car_id] => ferarri [total] => 15 ) [1] => Array ( [car_id] => lamborgini [total] => 10 ) [2] => Array ( [car_id] => ford [total] => 32 ) [3] => Array ( [car_id] => toyota [total] => 45 ) [4] => Array ( [car_id] => viar [total] => 1 ) ) 1
how do I make it look. horizontally displays the total. and vertical displays car brand.
You can use this
<?php
$car_tot = array(
'0' => array (
'car_id' => 'ferarri',
'total' => 15
),
'1' => array (
'car_id' => 'lamborgini',
'total' => 10
),
'2' => array (
'car_id' => 'ford',
'total' => 32
),
'3' => array (
'puskesmas_id' => 'toyota',
'total' => 45
),
'4' => array (
'car_id' => 'viar',
'total' => 1
)
);
echo '<pre>';
print_r( $car_tot );
echo '</pre>';
?>
<table>
<tr>
<th>Type</th>
<th>Total</th>
</tr>
<?php
foreach( $car_tot as $key=>$ctRow )
{
?>
<tr>
<td>
<?= !empty( $ctRow['car_id'] ) ? $ctRow['car_id'] : '';?>
</td>
<td>
<?= !empty( $ctRow['total'] ) ? $ctRow['total'] : '';?>
</td>
</tr>
<?php
}
?>
</table>

Looping through array of unlimited children and display to a table

I don't have any idea how to loop through this array and display it to an HTML table. Child data are dynamic and can be unlimited. Anyone can give me a clue? Thanks!
(
[0] => Array
(
[Discount] => Array
(
[id] => 8
[parent_id] => 0
[lft] => 1
[rght] => 6
[name] => Discount 1
[value] => 25
)
[children] => Array
(
[0] => Array
(
[Discount] => Array
(
[id] => 10
[parent_id] => 8
[lft] => 2
[rght] => 5
[name] => Child of D1
[value] => 32
)
[children] => Array
(
[0] => Array
(
[Discount] => Array
(
[id] => 11
[parent_id] => 10
[lft] => 3
[rght] => 4
[name] => The 1.1.1
[value] => 65
)
[children] => Array
(
)
)
)
)
)
)
)
I know I can't just do:
foreach($discounts as $discount){
echo "<div>{$discount['Discount']['name']}</div>";
}
Try this
foreach ($Discount as $children => $value) {
echo "<div>{$discount['Discount']['$children']['name']}</div>";
}
You will need recursion to properly generate the HTML. Here is an example that I hope is helpful. This isn't exactly HOW you'll want to generate the final HTML but this should get you started on the right track:
$data = array(
0 => array(
'discount' => array(
'id' => 8,
'parent_id' => 0,
'lft' => 1,
'rght' => 6,
'name' => 'Discount 1',
'value' => 25,
),
'children' => array(
0 => array(
'discount' => array(
'id' => 10,
'parent_id' => 8,
'lft' => 2,
'rght' => 5,
'name' => 'Child of D1',
'value' => 32,
),
'children' => array(
0 => array(
'discount' => array(
'id' => 11,
'parent_id' => 10,
'lft' => 3,
'rght' => 4,
'name' => 'The 1.1.1',
'value' => 65,
),
'children' => array(),
)
)
)
)
)
);
$html = getHtml($data);
/**
* This function is called recursively to generate the necessary HTML
* #param array $data
*/
function getHtml(array $data)
{
// This is your base conditon to end the recursion. It stops once it hits an empty children array
if (empty($data)) {
return;
}
$data = $data[0]; // will have to tweak this if you have more than 1 element per array
$html = sprintf('<div id="%d" name="%s">', $data['discount']['id'], $data['discount']['name']);
$html .= getHtml($data['children']); // this recursive call generates inner HTML
$html .= '</div>';
return $html;
}
// See the result
var_dump($html);

Categories