将值放入数组并使用array_sum

时间:2017-05-17 12:39:33

标签: php arrays mysqli array-sum

好吧,我有点卡住了,我知道这里有一个简单的事情,所以希望新鲜的眼睛会帮助

我在列中存储的值为2:7:99等,每个值由以下分隔:

现在我可以将所有值分开并查询另一个表以获得与该值对应的价格。

我遇到的问题是对所有价格值进行求和 见下面的代码 我认为最简单的方法是将所有价格值添加到数组中,然后执行array_sum()但由于某种原因我不能让它工作

**请不要提及SQL注入..它在LOCAL机器上没有外部访问权限,只有我自己才会使用这个

    <?php
include('config.php');
// Function for calculation Rough Invoice Total
function basicTotal() {
    $con = mysqli_connect("localhost","USER","PASS","TABLE");
    $wtbdq = mysqli_query($con,"SELECT * FROM `jobs` WHERE wsjid = '18'");
    $wtbdr = mysqli_fetch_assoc($wtbdq);
    do {
    $wtbd = explode(":",$wtbdr['worktobedone']);
    foreach($wtbd as $item) 
        {
            $priceq = mysqli_query($con,"SELECT * FROM `workshop-items` WHERE wsiid = '$item'");
            $pricer = mysqli_fetch_assoc($priceq);

            $price = array($pricer['incvat']);

            echo $item.' - '. $pricer['incvat'].'<br>';

        }

    } while($wtbdr = mysqli_fetch_assoc($wtbdq));

    $total = array_sum($price);
    echo $total;
}
basicTotal();
?>

提前致谢

3 个答案:

答案 0 :(得分:4)

just replace  $price = $pricer['incvat']; 

with this in your code

$price[] = $pricer['incvat'];

答案 1 :(得分:2)

您当前的方法存在的问题是您正在覆盖$price变量。您需要将$price数组中的值推送到$price[] = $pricer['incvat']。你需要这样做

    <?php
include('config.php');
// Function for calculation Rough Invoice Total
function basicTotal() {
    $con = mysqli_connect("localhost","USER","PASS","TABLE");
    $wtbdq = mysqli_query($con,"SELECT * FROM `jobs` WHERE wsjid = '18'");
    $wtbdr = mysqli_fetch_assoc($wtbdq);
    do {
    $wtbd = explode(":",$wtbdr['worktobedone']);
    foreach($wtbd as $item) 
        {
            $priceq = mysqli_query($con,"SELECT * FROM `workshop-items` WHERE wsiid = '$item'");
            $pricer = mysqli_fetch_assoc($priceq);

            $price[] = $pricer['incvat'];

            echo $item.' - '. $pricer['incvat'].'<br>';

        }

    } while($wtbdr = mysqli_fetch_assoc($wtbdq));

    $total = array_sum($price);
    echo $total;
}
basicTotal();
?>

答案 2 :(得分:2)

您一直在覆盖最终价格:

    private async void sendMessages_Click(object sender, EventArgs e)
    {
         await ServiceFacade.SendMessage("Hi to CEO");
         await ServiceFacade.SendMessage("Hi to Manager");
         await ServiceFacade.SendMessage("Hi to Team Leader");
    }

将其替换为:

   public class ServiceFacade
   {

   public  async Task SendMessage(string message)
   {

       //validates and formats message then calls PostAsync to send it on api service

       await PostAsync(string message);
   }

   private static async Task PostAsync(string message)
   {

       HttpWebRequest request = (HttpWebRequest)WebRequest.Create("hostname.com")
       //set up REQUEST ...
       var response = (HttpWebResponse)await request.GetResponseAsync();
   }

   }