简体   繁体   English

如何在php中拆分和求和逗号分隔的多行值

[英]How to split and sum comma separated multiple line values in php

I have one issue.我有一个问题。 How can i split and sum up multiple comma separated line values in php.如何在 php.ini 中拆分和总结多个逗号分隔的行值。 Following my mysql table screenshot按照我的mysql表截图在此处输入图片说明

here my date wise miles filter page这里是我的日期明智里程过滤页面

在此处输入图片说明

I want to output miles colums like following when users enter from and to date.我想在用户输入日期和日期时输出英里列,如下所示。

IA      59.62
MD       7.88    
IL     359.22

Total Miles : 426.72

How can i achieve this in php? Please help me.


my php code:我的 php 代码:

<?php
// Range.php
if(isset($_POST["From"], $_POST["to"]))
{
    $conn = mysqli_connect("localhost", "root", "", "truckinvo");

    $result = '';
    $query = "SELECT * FROM tble_states_miles WHERE order_date BETWEEN '".$_POST["From"]."' AND '".$_POST["to"]."'";
    $sql = mysqli_query($conn, $query);
    ?>
    <table class="table table-bordered">
    <tr>
Total Miles from the date between <?php echo $_POST["From"]; ?> to <?php echo $_POST["to"]; ?>  
<th width="40%">Miles</th>
    </tr>
    <?php
    if(mysqli_num_rows($sql) > 0)
    {
        while($row = mysqli_fetch_array($sql))
        {
            ?>
            <tr>


            <td>
            <?php 

            echo nl2br($row["miles"]); ?></td>
            </tr>
            <?php
        }
    }
    else
    {
    ?>

        <tr>
        <td colspan="5">No Data Found</td>
        </tr>
        <?php
    }
    ?>
    </table>
    <?php   echo $result; }
?>

I tried to use following code to split我尝试使用以下代码进行拆分

<?php
    $f1 = preg_replace('/,\\s*/', "', '", $row["miles"]);
$f2 = preg_replace('/\\n/', "'), \n('", $f1);
?>
    <?php echo $f2;  ?>

Break per line, break each row to parts, display the name and sum up the values.每行拆分,将每一行拆分为多个部分,显示名称并汇总值。 Try:尝试:

Before the loop:循环前:

<?php $totalMiles = 0 ?>

Instead of:代替:

<td>
<?php 
  echo nl2br($row["miles"]); ?>
</td>

In the loop:在循环:

<td>
<?php
    // iterate per state
    foreach (explode("\n", $row['miles']) as $stateRow) {
        // prepare the parts, we don't want any whitespace
        $stateParts = array_filter(array_map('trim', explode(',', $stateRow)));

        // the state's name (the first part)
        $stateName = $stateParts[0];

        // sum everything in the array
        // this works, because the name will get cast to "0"
        // try it: echo (int) 'IL';
        $stateMiles = array_sum($stateParts);

        // total mileage sum
        $totalMiles += $stateMiles;

        // display the result, any way you want
        printf('%s miles %.2f', $stateName, $stateMiles);
    }
?>
</td>

After the loop:循环后:

Total miles <?= $totalMiles ?>

And please, use prepared statements , your application is unsecure.并且请使用准备好的语句,您的应用程序是不安全的。

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

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