简体   繁体   中英

Adding up prices in foreach loop (PHP) - Not adding up

... It's not as silly as it sounds...

I have the following code, which is used by my ajax table script to display database stuff on the page in a table.

foreach($ct->data as $key => $value){
    $ct->data[$key][2]='<a href="quantity.php?partno='.$ct->data[$key][0].'&description='.$ct->data[$key][1].'&quantity='.$ct->data[$key][2].'&order='.$o.'">'.$ct->data[$key][2].'</a>';
    $ct->data[$key][3]='<a href="quantity.php?partno='.$ct->data[$key][0].'&description='.$ct->data[$key][1].'&price='.$ct->data[$key][3].'&order='.$o.'">'.$ct->data[$key][3].'</a>';

    if($ct->data[$key][4] == "" || $ct->data[$key][4] == null)
        $ct->data[$key][4]='<a href="freight.php?partno='.$ct->data[$key][0].'&description='.$ct->data[$key][1].'&freight='.$ct->data[$key][4].'&order='.$o.'">Edit Charge.</a>';
    else
        $ct->data[$key][4]='<a href="freight.php?partno='.$ct->data[$key][0].'&description='.$ct->data[$key][1].'&freight='.$ct->data[$key][4].'&order='.$o.'">'.$ct->data[$key][4].'</a>';

    $Total =$Total+ $ct->data[$key][3];
    $freight =$freight+ $ct->data[$key][4];
}

And as you can see, in the foreach loop, I am trying to add up the contents of 2 columns.

The $Total column or, $ct->data[$key][3] lists the Prices for each row of products, and the $freight column does the same for each row of Freight charges.

And inside the foreach loop, I am trying to add together the total amount of prices, and Freight charges.

I'm not sure if I'm doing it the right way, because when I check the database, it just adds '0' (without the quotes). So it's not adding up!

For example, if there are a total of 3 rows in the table, and each product is 1 (dollar), it should add up to 3, right? And same goes for the $freight ones.

Can someone please tell me what I'm doing wrong here?

You are setting data[$key][3] equal to some HTML hyper link. Its not something that can be "totalled"

Is line 3 not setting the value you're adding to $Total to a string?

$ct->data[$key][3]='<a href="quantity.php?partno='.$ct->data[$key][0].'&description='.$ct->data[$key][1].'&price='.$ct->data[$key][3].'&order='.$o.'">'.$ct->data[$key][3].'</a>';

and then

$Total =$Total+ $ct->data[$key][3];

If you remove the first one, the second might work better.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM