'Undefined index' error when using foreach loop - php

I've 2 tables named preacher & Sermons
Fields of Preacher
preacher_id
first_name
last_name
preacher_image
preacher_logo
preacher_bio_brief
category
fields of sermons
sermon_id
preacher_id
sermon_title
sermon_image
audio_file
sermon_description
sort_order
I want to display all the sermons of each preacher by the order of preacher first_name.I got it properly but also got the below error
A PHP Error was encountered
Severity: Notice
Message: Undefined index: 1
Filename: home/sermons_view.php
Line Number: 27
method in controller
function index() {
$res = $this->sermon_model->viewAllpreachers();
$this->data['preachers'] = $res;
$this->data['page'] = $this->config->item('APP_template_dir') . 'site/home/ sermons_view';
$this->load->vars($this->data);
$this->load->view($this->_container);
}
Method in model
function viewAllpreachers() {
$preacher = array();
$this->db->select('*');
$this->db->from('preacher');
$this->db->order_by('first_name');
$query = $this->db->get();
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$preacher[$row->preacher_id]['preacher_id'] = $row->preacher_id;
$preacher[$row->preacher_id]['preacher_name'] = $row->first_name . ' ' . $row->last_name;
$preacher[$row->preacher_id]['preacher_image'] = $row->preacher_image;
$preacher[$row->preacher_id]['preacher_bio_brief'] = $row->preacher_bio_brief;
$this->db->select('*');
$this->db->from('sermons');
$this->db->where('preacher_id',$row->preacher_id);
$query = $this->db->get();
if ($query->num_rows() > 0) {
foreach ($query->result() as $row1) {
$preacher[$row1->preacher_id][$row1->sermon_id]['sermon_id'] = $row1->sermon_id;
$preacher[$row1->preacher_id][$row1->sermon_id]['preacher_id'] = $row1->preacher_id;
$preacher[$row1->preacher_id][$row1->sermon_id]['sermon_image'] = $row1->sermon_image;
$preacher[$row1->preacher_id][$row1->sermon_id]['sermon_title'] = $row1->sermon_title;
$preacher[$row1->preacher_id][$row1->sermon_id]['audio_file'] = $row1->audio_file;
$preacher[$row1->preacher_id][$row1->sermon_id]['sermon_description'] = $row1->sermon_description;
}
}
}
return $preacher;
}
return false;
}
code in View
<?php
if ($preachers) {
foreach ($preachers as $val) {
?>
<tr>
<td><img src="<?= base_url(); ?>uploads/<?= $val['preacher_image']; ?>"/></td>
<td colspan="2"><?= $val['preacher_name']; ?></td>
<td colspan="2"><?= $val['preacher_bio_brief']; ?></td>
</tr>
<?
echo '<pre>';
//print_r($val);
echo '</pre>';
foreach ($val as $val1) {
?>
<tr>
<td style="padding-left: 50px; "><img src="<?= base_url(); ?>uploads/<?= $val1['sermon_image']; ?>" style="width: 60px;height: 60px;"/></td>
<td><?= $val1['sermon_title']; ?></td>
<td><?= $val1['audio_file']; ?></td>
<td width="250px"><?php $res = explode('/', $val1['audio_file']);
if ($val1['audio_file']) {
?><a id="play" href="<?= site_url('sermons/playmp3/' . $val1['sermon_id']); ?>"><?= $res['1']; ?></a><?php } ?></td>
<td><?= $val1['audio_file']; ?></td>
</tr>
<?
}
}
}
?>
I think its the problem with the resultant array
I got that like
Array
(
[21] => Array
(
[preacher_id] => 21
[preacher_name] => Vance Havner
[preacher_image] => profile_image/havner.jpeg
[preacher_bio_brief] => this is for testing
[42] => Array
(
[sermon_id] => 42
[preacher_id] => 21
[sermon_image] => sermon_image/image_81322797345.jpg
[sermon_title] => 3 notes of the devil's tales
[audio_file] => audio_file/Niranja_Mizhiyum1.mp3
[sermon_description] => 3 notes of the devil's tales
)
[41] => Array
(
[sermon_id] => 41
[preacher_id] => 21
[sermon_image] =>
[sermon_title] => The Lordship of Christs
[audio_file] => audio_file/Naladhamayanthi_Kadhayile.mp3
[sermon_description] => the lordship of christ
)
)
)

there is no $res in your model
first debug what is $res with print_r($res) and
AFAIK there must be $val1['sermon_title'] instead of $res['1']

Related

get td values display as static in codeigniter

Hi guys i am trying to display the first td values as static so i have keep those values in one array and i try to increase the values and try to display but when i get it is displaying depending on foreach values if i have one record in foreach it is displaying one value and if i have 2 records it is displaying 2 values.
But i want to display all td value if i have values in foreach or not also.
Here is my code:
<tbody>
<?php
$arr = array(0=>'On Hold',1=>'Asset Incomplete',2=>'SME Discussion',3=>'a',4=>'b',5=>'c',6=>'d',7=>'e',8=>'f',9=>'g',10=>'h');
$i = 0;
foreach($getCourse as $report)
$status= $report->status;
{
?>
<tr>
<td><?php echo $arr[$i]; ?>
<?php $i++; ?></td>
<td><?php
if($status==1)
{
echo "On Hold";
}
elseif($status==2)
{
echo "Asset Incomplete";
}
elseif($status==3)
{
echo "Yet to Start";
}
elseif($status==4)
{
echo "SME Discussion";
}
elseif($status==5)
{
echo "Development";
}
elseif($status==6)
{
echo "PB Review";
}
elseif($status==7)
{
echo "PB Fixes";
}
elseif($status==8)
{
echo "PB2 Review";
}
elseif($status==9)
{
echo "PB2 Fixes";
}
elseif($status==10)
{
echo "Alpha Development";
}
elseif($status==11)
{
echo "Alpha Review";
}
elseif($status==12)
{
echo "Alpha Fixes";
}
elseif($status==13)
{
echo "Beta Review";
}
elseif($status==14)
{
echo "Beta Fixes";
}
elseif($status==15)
{
echo "Gamma";
}
?></td>
<td><?php echo $report->coursename; ?></td>
<td><?php echo $report->statuscount;?></td>
<td></td>
</tr>
<?php
}
?>
</tbody>
Here is my controller:
public function index()
{
if ($this->session->userdata('is_logged')) {
$data['getCourse']=$this->Report_model->getTopicReports();
$this->load->view('template/header');
$this->load->view('reports/report',$data);
$this->load->view('template/footer');
}
else {
redirect("Login");
}
}
Here is my model:
public function getTopicReports()
{
$this->db->select('count(t.status) as statuscount,t.topicName as topicname,c.coursename,t.status')
->from('topics t')
->join('course c', 't.courseId = c.id')
->where('t.courseid',1)
->where('t.status',5);
$query = $this->db->get();
return $query->result();
}
This is how i want to display here is my referrence image:
Can anyone help me how to do that thanks in advance.
FINAL UPDATED & WORKING VERSION
For me this was tricky. This turned out to be what I felt to be a awkward indexing issue.
The problem is that your data is not optimized very well to accommodate the task you are asking for. You have to make odd comparisons as you traverse the table. I was able to get it accomplished.
I would actually be very interested in seeing a more refined approach. But until that happens this code will dynamically generate a table that matches the output of the sample pictures that you posted in your question.
I have tested this code with some sample data that matches the array structure that you posted in your comments.
Here is the code:
//Create an array with your status values.
$rowName = array(
'On Hold',
'Asset Incomplete',
'Yet to Start',
'SME Discussion',
'Development',
'PB Review',
'PB Fixes',
'PB2 Review',
'PB2 Fixes',
'Alpha Development',
'Alpha Review',
'Alpha Fixes',
'Beta Review',
'Beta Fixes',
'Gamma'
);
//Generate a list of class names and get rid of any duplicates.
foreach($getCourse as $report){
$courseNames[] = $report->coursename;
}
$courseNames = array_unique($courseNames);
//Create the header.
echo
'<table>
<thead>
<tr>
<th>#</th>';
foreach($courseNames as $course){
echo '<th>' . $course . '</td>';
}
echo
'<th>Total</th>
</tr>
</thead>
<tbody>';
//Iterate across the array(list) of status values.
for($i = 0; $i < count($rowName); $i++){
echo
'<tr>';
echo '<td>' . $rowName[$i] . '</td>';
//Iterate through all combinations of class names and status values.
for($j = 0; $j < count($courseNames); $j++){
//Set flags and intial values.
$found = FALSE;
$total = 0;
$value = NULL;
for($k = 0; $k < count($getCourse); $k++){
//***Note - The ""$getCourse[$k]->status - 1" is because the status values in your data do not appear
//to start with an index of 0. Had to adjust for that.
//Sum up all the values for matching status values.
if(($getCourse[$k]->status - 1) == $i){
$total += $getCourse[$k]->statuscount;
}
//Here we are checking that status row and the status value match and that the class names match.
//If they do we set some values and generate a table cell value.
if(($getCourse[$k]->status - 1) == $i && $courseNames[$j] == $getCourse[$k]->coursename){
//Set flags and values for later.
$found = TRUE;
$value = $k;
}
}
//Use flags and values to generate your data onto the table.
if($found){
echo '<td>' . $getCourse[$value]->statuscount . '</td>';
}else{
echo '<td>' . '0' . '</td>';
}
}
echo '<td>' . $total . '</td>';
echo
'</tr>';
}
echo '</tbody>
</table>';
Try this. I am storing course status in $used_status then displaying the remaining status which are not displayed in foreach.
$arr = array ( '1' =>'On Hold', '2' => 'Asset Incomplete', '3' => 'SME Discussion', '4' => 'a', '5' => 'b', '6' => 'c', '7' =>'d', '8' => 'e', '9' => 'f', '10' => 'g', '11' => 'h' );
$used_status = array();
foreach($getCourse as $report) { ?>
<tr>
<td>
<?php $course_status = isset($arr[$report->status]) ? $arr[$report->status] : "-";
echo $course_status;
$used_status[] = $course_status; ?>
</td>
<td>
<?php echo $report->coursename; ?>
</td>
<td>
<?php echo $report->statuscount; ?>
</td>
</tr>
<?php }
foreach($arr as $status) {
if(!in_array($status, $used_status)) { ?>
<tr>
<td>
<?php echo $status; ?>
</td>
<td>
<?php echo "-"; ?>
</td>
<td>
<?php echo "-"; ?>
</td>
</tr>
<?php }
} ?>

how to display data from an array in a table am getting errors

hi all i am trying to display array of data in a table .but the main task is i need to display all users that are under one supervisor, they may/may not have attempted the test .i am using if else condition in controller but am getting error like
Message: Undefined index: status and Message: Undefined index:
submittimestamp
below is my code
controller:
if ($supervisor) {
$users_query="SELECT u.* ,v.value FROM usr_data u, udf_text v WHERE u.usr_id != 6 AND u.usr_id = v.usr_id " . $supervisor_condition . " GROUP BY u.usr_id";
// echo $users_query;
$user_records = $this->base_model->executeSelectQuery($users_query);
$final_dataa = [];
foreach ($user_records as $user) {
$user=(object)$user;
$user_test=" SELECT u.*,o.title,ta.*,tpr.workingtime, tpr.pass, tpr.tstamp, tpr.points, tpr.maxpoints, tm.minimum_level, tcr.mark_official,(tcr.reached_points/tcr.max_points)*100 as result,v.value,ta.submittimestamp,tcr.mark_official FROM usr_data u, object_data o,tst_tests tt,tst_active ta,tst_pass_result tpr, tst_result_cache tcr,udf_text v, tst_mark tm WHERE u.usr_id != 6 AND u.usr_id=ta.user_fi AND tt.obj_fi=o.obj_id AND v.usr_id=u.usr_id AND ta.test_fi=tt.test_id AND tt.test_id = tm.test_fi AND tcr.active_fi=ta.active_id AND tm.passed = 1 AND ta.active_id=tpr.active_fi AND tcr.active_fi=ta.active_id AND v.field_id='2' AND ta.user_fi = $user->usr_id GROUP by ta.submittimestamp";
// echo $user_test;
$tst_records=$this->base_model->executeSelectQuery($user_test);
if (count($tst_records)) {
foreach ($tst_records as $tst) {
$tst=(object)$tst;
$dta['usr_id'] = $user->usr_id;
$dta['firstname'] = $user->firstname;
$dta['matriculation'] = $user->matriculation;
$dta['approve_date'] = $this->udfTextData(1, $user->usr_id);
$dta['department'] = $user->department;
$dta['job_title'] = $this->udfTextData(6, $user->usr_id);
$dta['submittimestamp'] = $tst->submittimestamp;
$dta['test_title'] = $tst->title;
$dta['division'] = $tst->value;
$mark_official = $tst->mark_official;
if ($mark_official == "passed" || $mark_official == "Passed" || $mark_official == "PASSED") {
$result_status = '<span class="label label-primary"> Completed </span>';
$completed = TRUE;
} else {
$result_status = '<span class="label label-danger"> Failed </span>';
$failed = TRUE;
}
$dta['status'] = $result_status;
$final_dataa[] = $dta;
}
}
else{
$dta['usr_id'] = $user->usr_id;
$dta['firstname'] = $user->firstname;
$dta['matriculation'] = $user->matriculation;
$dta['approve_date'] = $this->udfTextData(1, $user->usr_id);
$dta['department'] = $user->department;
$dta['job_title'] = $this->udfTextData(6, $user->usr_id);
$dta['test_title'] = $user->title;
$dta['division'] = $user->value;
$final_dataa[] = $dta;
}
}
}
$dataa['recordss'] = $final_dataa;
$this->load->view('supervisor', $dataa);
I am using if else condition if users have test else not like that .below is my view code
view:
<h3> Skill Matrix Report Process Based Training Record in LMS </h3>
<hr>
<?php $uniq_rec = array_unique($recordss,SORT_REGULAR);
// var_dump($uniq_rec);
$uniq_name = array_unique(array_column($recordss, 'firstname'));
$uniq_test = array_unique(array_column($recordss, 'test_title'));
?>
<table class="table" id="myTable">
<thead>
<tr>
<th>Employe NO</th>
<th>Employe Name</th>
<th>Date Joined</th>
<th>division</th>
<th>department</th>
<th>jobtitle</th>
<?php
foreach ($uniq_test as $row) {
?>
<th><?php echo $row?></th>
<?php
}
?>
</tr>
</thead>
<tbody>
<?php
foreach ($uniq_rec as $row) {
$row = (object)$row;
// var_dump($row);
$date_joined_y = substr($row->approve_date,0,4);
$date_joined_m = substr($row->approve_date,4,2);
$date_joined_d = substr($row->approve_date,6,2);
$date_joined = $date_joined_d."-".$date_joined_m."-".$date_joined_y;
?>
<tr>
<td><?php echo ucfirst($row->matriculation); ?></td>
<td><?php echo $row->firstname?></td>
<td> <?php echo ucfirst($date_joined); ?></td>
<td><?php echo ucfirst($row->division); ?></td>
<td><?php echo ucfirst($row->department); ?></td>
<td><?php echo ucfirst($row->job_title); ?></td>
<?php
foreach ($uniq_test as $uniq) {;
$status = "";
foreach ($recordss as $rec) {
if($uniq == $rec['test_title'] && $rec['firstname'] == $row->firstname){
echo "<td>".$rec['status'].$rec['submittimestamp']."</td>";
$status = "true";
}
}
if($status != "true"){
echo "<td></td>";
}
$status = "";
}
?>
but the main task is i need to display all users who are attempted test or not but those users are under one Supervisor
submittimestampbut the main task is i need to display all users who are attempted test or not but those users are under one Supervisor.i am using if else condition in controller but am getting error like
Message: Undefined index: status and Message: Undefined index:
submittimestamp

Match column and row, then print data

I am having two set off arrays, first array is holding data about colors, second about dimensions.
$colors= array(
"27" => "RAL 9002",
"255" => "RAL 9006",
"341" => "RAL 8019",
"286" => "RAL 7016",
"141" => "RAL 3009",
"171" => "RAL 6028",
"121" => "RAL 8004",
"221" => "RAL 5010",
"101" => "RAL 3000",
"273" => "RAL 9007",);
$dimensions = array
(
array(0.3,1245),
array(0.35,1245),
array(0.40,1100),
array(0.45,1245),
array(0.50,1245),
array(0.60,1245),
array(0.70,1245),
);
Values above are used for queries. I wanted to make an array which will hold data, and later in comparison will print data. Query can return result NULL
foreach($colors as $key => $value)
{
//print "Boja $key . <br>";
foreach($dimensions as $data )
{
//print "Debljina $data[0], Sirina $data[1] Boja $key <br>";
$sql = "SELECT Debljina, Sirina, sum(Kolicina) as suma
FROM jos_ib_repromaterijali WHERE Debljina = '$data[0]' AND Sirina = '$data[1]' AND Boja = '$key'";
$q = $conn -> query($sql);
$vrijednosti = array();
while($r=$q->fetch()) {
$debljina = $r['Debljina'];
$sirina = $r['Sirina'];
$kolicina = $r['suma'];
$vrijednosti[] = $debljina . $sirina . $kod . $kolicina;
}
}
}
Once I get results, I create html table
<div class="col-lg-6">
<table class="table table-bordered">
<thead>
<tr>
<th><?php echo "Dimenzije"; ?> </th>
<?php foreach($colors as $boja) { ?>
<th><?php echo $boja; ?> </th>
<?php } ?>
</tr>
</thead>
<tbody>
<?php foreach($dimensions as $dim) {
?>
<tr>
<td><?php echo $dim[0] . ' X ' . $dim[1]; ?> </td>
<td><?php
if (isset($vrijednosti[$dim[0] . $dim[1]])) {
echo "asdas";
}
else {
echo "error";
}
?> </td>
</tr>
<?php }
?>
</tbody>
</table>
Table print headers and dimensions as it should, I am having trouble in matching rows with column. If someone give me an advice it would be appreciated.
Query can give result NULL; if that is result It should print 0 below color for specific row.

Undefined variable,index error fetching data codeigniter

Im fetching data from a table to another table that will be shown in my dashboard page for a user after loggin in.
But there is a problem with the indexes, i got this error:
Here is the line error:
Here is my code:
My view file ("usuario"):
<thead>
<th>id</th>
<th>User</th>
<th>Subject</th>
<th>Grade</th>
<th>Date</th>
</thead>
<tbody>
<?php
if (count($records) > 0 && $records != false) {
foreach($records as $record) {
echo "<tr>
<td>".$record['id']."</td>
<td>".$record['User']."</td>
<td>".$record['name']."</td>
<td>".$record['grade']."</td>
<td>".$record['date']."</td>
</tr>";
}
}
?>
</tbody>
</body>
</html>
My controller file ("login"):
public function home(){
$data['record']=$this->m_login->getDetails();
$this->load->view('usuario',$data);
}
My model file ("m_login"):
public function getDetails()
{
$st=$this->db->SELECT('cursadas.*, usuarios.name as usuarios, materias.name as materias_name')->from('cursadas')
->join('usuarios','usuarios.id=cursadas.user_id')
->join('materias','materias.id=cursadas.subject_id')
->WHERE('cursadas.user_id=',$this->session->userdata['id'])
->get()->result_array();
return $st[0];
}
You have the variable $records on view but not on controller
Change
$data['record'] = $this->m_login->getDetails();
To
// add this array() just in case no results found
$data['records'] = array();
$data['records'] = $this->m_login->getDetails();
$this->load->view('usuario', $data);
Another way is on controller
$results = $this->m_login->getDetails();
$data['records'] = array();
if ($results) {
foreach ($results as $result) {
$data['records'][] = array(
'id' => $result['id'],
'User' => $result['User'],
'name' => $result['name'],
'grade' => $result['grade'],
'date' => $result['date']
);
}
}
$this->load->view('usuario',$data);
View
<?php if ($records) {?>
<?php foreach($records as $record) {?>
<tr>
<td><?php echo $record['id'];?></td>
<td><?php echo $record['User'];?></td>
<td><?php echo $record['name'];?></td>
<td><?php echo $record['grade'];?></td>
<td><?php echo $record['date'];?></td>
</tr>
<?php } ?>
<?php } else { ?>
<tr>
<td>No Results Found</td>
</tr>
<?php } ?>
Wrong array index in your controller.
Change this
$data['record']=$this->m_login->getDetails();
to
$data['records']=$this->m_login->getDetails();
result_array() return returns result with array so you need to it like this -
if (count($record) > 0 && $record != false) {
foreach($record as $rec){
echo "<tr>
<td>".$rec['id']."</td>
<td>".$rec['User']."</td>
<td>".$rec['name']."</td>
<td>".$rec['grade']."</td>
<td>".$rec['date']."</td>
</tr>";
}
}
Please check this from above code and comment if you have any problem

how can i write an algorithm to multiply the total * quantity in a shopping cart using php $_SESSION?

I am writing a shopping cart and have my data stored in the $_SESSION array, but would like to calculate a total. below it the code I thought would work to do this, but it returns '1' in stead of a total!
$total = array($_SESSION['qty'],$_SESSION['pr']);
/* I'll give you more code...thanks for your help!!
here is the code for my php cart:
<?php
function item_list()
{
if(isset($_SESSION['qty'])){
$total = array($_SESSION['qty'],$_SESSION['pr']);
foreach($_SESSION['qty'] as $key => $value)
{?>
<tr>
<td align="center"><?php echo $_SESSION['item'][$key]; ?></td>
<td align="center"><?php echo $value; ?></td>
<td align="center"><?php echo $_SESSION['pr'][$key]; ?></td>
<td align="center"><?php echo array_product($total); ?>
</tr><?php
}
}
}
session_start();
if(isset($_POST['clear']) && ($_POST['clear'] == 'clear'))
{
session_destroy();
unset($_SESSION['qty']);
unset($_SESSION['item']);
unset($_SESSION['pr']);
unset($_POST['qty']);
unset($_POST['item']);
unset($_POST['pr']);
}
if(!isset($_SESSION['qty'])) $_SESSION['qty'] = array();
if(!isset($_SESSION['item'])) $_SESSION['item'] = array();
if(!isset($_SESSION['pr'])) $_SESSION['pr'] = array();
if(isset($_POST['qty']))
{
foreach($_POST['qty'] as $value)
{
if(!$value == '') array_push($_SESSION['qty'], filter_var($value,
FILTER_SANITIZE_SPECIAL_CHARS));
}
foreach($_POST['item'] as $key => $value)
{
if(!$_POST['qty'][$key] == '') array_push($_SESSION['item'], filter_var($value,
FILTER_SANITIZE_SPECIAL_CHARS));
}
foreach($_POST['pr'] as $key => $value)
{
if(!$_POST['qty'][$key] == '') array_push($_SESSION['pr'], filter_var($value,
FILTER_SANITIZE_SPECIAL_CHARS));
}
}
?>
That is a strange way to structure a shopping cart, but here's how to do it with that structure:
foreach($_SESSION['qty'] as $key => $value)
{
$total = $_SESSION['qty'][$key] * $_SESSION['pr'][$key];
?>
<tr>
<td align="center"><?php echo $_SESSION['item'][$key]; ?></td>
<td align="center"><?php echo $value; ?></td>
<td align="center"><?php echo $_SESSION['pr'][$key]; ?></td>
<td align="center"><?php echo $total; ?>
</tr><?php
}
If you wanted to get a total of all quantity and cost of the cart:
function getTotals()
{
$total = array('qty' => 0, 'price' => 0);
foreach($_SESSION['qty'] as $key => $qty)
{
$total['qty'] += $qty;
$total['price'] += ($_SESSION['pr'][$key] * $qty)
}
return $total;
}
$total = getTotals();
echo $total['qty']; // output the total quantity of items
echo $total['price']; // output the total cost for all items and quantity
I would recommend a better structure though, something like:
$_SESSION['cart']['items'] = array(
array(
'name' => 'Screwdriver',
'price' => 5,
'qty' => 2,
),
array(
'name' => 'Hammer',
'price' => 10,
'qty' => 1,
)
);
As per your cart array it is not able to hold multiple products you have to use multy dimensional array like this
$_SESSION['cart_items'] = array(
array( "qty"=>5, "item"=>"tshirt", "pr"=>50.20),
array( "qty"=>2, "item"=>"Cell Phone", "pr"=>50.20),
array( "qty"=>7, "item"=>"", "pr"=>50.20),
)
then you can write your code like this
function item_list()
{
foreach($_SESSION['cart_items'] as $item_array)
{?>
<tr>
<td align="center">Item:<?php echo $item_array['item']; ?></td>
<td align="center">Qty: <?php echo $item_array['qty']; ?></td>
<td align="center">Price :<?php echo $item_array['pr']; ?></td>
<td align="center">Total : <?php echo $item_array['qty'] * $item_array['pr']; ?>
</tr><?php
}
}
You should create yourself a Card class that is able to import/export data from the $_SESSION superglobal (or some other array if you mock it for tests, testing with $_SESSION can be akward) which is able to handle your data-structure easily and can calculate the total, too:
$cart = new Cart();
$cart->importFromArray($_SESSION);
// or:
$cart->importFromArray($_SESSION['cart']);
// later on:
$total = $cart->getTotal();
// somewhere else:
$cart->addItem(...);
...
$_SESSION['cart'] = $cart->exportToArray();
That will allow you to more easily change the code over time.

Categories