简体   繁体   English

在PHP中添加多个变量的总和

[英]adding up sums of multiple variables in php

ok

so I have been stuck on this problem for a while and I'm sure there is a more elegant way of doing it. 因此我已经在这个问题上停留了一段时间,而且我敢肯定有一种更优雅的方法可以解决此问题。

I have 3 columns in a database - 我在数据库中有3列-

Stand1 | Stand1 | Stand2 | Stand2 | Stand3 展位3

each column will either have a stand number (ie D30) or 'Not Assigned' 每列将有一个展位号(即D30)或“未分配”

What I need to do is count how many stands have been assigned to that customer. 我需要做的是计算已为该客户分配了多少个展位。

For example : 例如 :

D30 | D30 | not assigned | 未分配 not assigned would = 1 未分配将= 1

D30 | D30 | B30 | B30 | E30 = 3 E30 = 3

The code I have so far is 我到目前为止的代码是

if ($row["stand1"] == 'Not Assigned') {
    $stand1 = '0';
}  
else {
    $stand1 = '1';
}

if ($row["stand2"] == 'Not Assigned') {
    $stand2 = '0';
}  
else {
    $stand2 = '1';
}

if ($row["stand3"] == 'Not Assigned') {
    $stand3 = '0';
}  
else {
    $stand3 = '1';
}

I then thought I could try and count how many stand were assigned : 然后我以为我可以尝试计算分配了多少个展位:

$standcount = $stand1 + $stand2 + $stand3

But when I print this out (everything else is in an array so loops through every customer) all I get is the total 3 for every customer. 但是,当我将其打印出来时(其他所有元素都位于一个数组中,因此遍历每个客户)我得到的是每个客户的总数3。

I tried saving the data into an array like: 我尝试将数据保存到一个数组中,例如:

$standcount = array($stand1, $stand2, $stand3); 

But I get the same result. 但我得到相同的结果。 I thought a foreach loop may work but not sure how to do it. 我认为foreach循环可能有效,但不确定如何执行。

I would suggest you to: 我建议您:

  1. Set the columns' default value to NULL , so that if no value is provided in an entry you'll have a null value instead of a string (that can contains different letters, as in your case). 将列的默认值设置为NULL ,这样,如果条目中未提供任何值,则您将拥有一个null值,而不是一个字符串(根据您的情况,该字符串可以包含不同的字母)。 After that you can simply perform the isset() check against each value. 之后,您可以简单地对每个值执行isset()检查。
  2. Use a function to avoid code repetition (the main source of errors), something like: 使用一个函数来避免代码重复(错误的主要来源),例如:

     function check($value) { return (isset($value)) ? 1 : 0; } $stand_1 = check($row["stand1"]); $stand_2 = check($row["stand2"]); $stand_3 = check($row["stand3"]); 

If you instead want to use a string as "Not Assigned" or "NA", you can perform a case-insensitive check with strcasecmp() between the strings in case, for any reason, a value contains an extra space or a lower-case letter. 如果您想将字符串用作“未分配”或“ NA”,则可以在字符串之间使用strcasecmp()执行不区分大小写的检查,以防万一由于某种原因,值包含多余的空格或小写的值。案例信。 In this case the check function would be: 在这种情况下,检查功能为:

function check($str) {
    return (strcasecmp($str, "NA") == 0) ? 0 : 1;
}
$stand_1 = check($row["stand1"]);
$stand_2 = check($row["stand2"]);
$stand_3 = check($row["stand3"]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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