简体   繁体   English

重建PHP数组以正确地将数据拟合到html表中

[英]Reconstruct PHP array to fit data into html table correctly

I'm trying to display data that shows the count for each month for locations in Jan-December. 我正在尝试显示数据,显示1月至12月期间每个月的计数。

I wrote the query to get the necessary data from the server but when I display it in the view in my table the layout for the data, doesn't look the way I want it to look like in my table. 我编写了查询以从服务器获取必要的数据,但是当我在表格的视图中显示数据的布局时,看起来并不像我希望它在我的表格中看起来那样。 I believe I have to reconstruct the array that I wrote in the query for the right format first and then I can display it in my table? 我相信我必须首先重构我在查询中为正确格式编写的数组,然后我可以在我的表中显示它?

Right now, the data that comes back from the server looks like so 现在,从服务器返回的数据看起来就像这样

 <table id="registeredTable" class="table table-striped table-bordered table-hover"> <thead> <tr> <th>Locations</th> <th>January</th> <th>Feburary</th> <th>March</th> <th>April</th> <th>May</th> <th>June</th> <th>July</th> <th>August</th> <th>September</th> <th>October</th> <th>November</th> <th>December</th> </tr> </thead> <tbody> <?php foreach($selectAllmonthlylocations as $item) { echo ' <tr> <td>'.$item["locations"].'</td> <td>'.$item["Total"].'</td> </tr> '; } ?> </tbody> </table> 

So my question is how can I format my array properly to display it in my table how I want? 所以我的问题是如何正确格式化我的数组以在我的表中显示我想要的?

Array
(
    [0] => Array
        (
            [usergroup] => Austin_Domestic
            [DateAdded] => 2018-01-03
            [Total] => 15
        )

    [1] => Array
        (
            [usergroup] => Austin_International
            [DateAdded] => 2018-01-25
            [Total] => 2
        )

    [2] => Array
        (
            [usergroup] => BayArea_Domestic
            [DateAdded] => 2018-01-16
            [Total] => 192
        )

    [3] => Array
        (
            [usergroup] => BayArea_International
            [DateAdded] => 2018-01-05
            [Total] => 28
        )

    [4] => Array
        (
            [usergroup] => Bengaluru_Domestic
            [DateAdded] => 2018-01-10
            [Total] => 2
        )

    [5] => Array
        (
            [usergroup] => Bengaluru_International
            [DateAdded] => 2018-01-05
            [Total] => 1
        )

    [6] => Array
        (
            [usergroup] => Cork
            [DateAdded] => 2018-01-02
            [Total] => 31
        )

    [7] => Array
        (
            [usergroup] => CulverCity
            [DateAdded] => 2018-01-10
            [Total] => 3
        )

    [8] => Array
        (
            [usergroup] => Denver
            [DateAdded] => 2018-01-10
            [Total] => 1
        )

    [9] => Array
        (
            [usergroup] => Hyderabad
            [DateAdded] => 2018-01-05
            [Total] => 3
        )

    [10] => Array
        (
            [usergroup] => London
            [DateAdded] => 2018-01-02
            [Total] => 10
        )

    [11] => Array
        (
            [usergroup] => Macau
            [DateAdded] => 2018-01-17
            [Total] => 1
        )

    [12] => Array
        (
            [usergroup] => Munich
            [DateAdded] => 2018-01-02
            [Total] => 6
        )

    [13] => Array
        (
            [usergroup] => Sacramento_Domestic
            [DateAdded] => 2018-01-04
            [Total] => 1
        )

    [14] => Array
        (
            [usergroup] => Shanghai
            [DateAdded] => 2018-01-12
            [Total] => 2
        )

    [15] => Array
        (
            [usergroup] => Singapore
            [DateAdded] => 2018-01-03
            [Total] => 8
        )

    [16] => Array
        (
            [usergroup] => Sydney
            [DateAdded] => 2018-01-21
            [Total] => 1
        )

    [17] => Array
        (
            [usergroup] => Tokyo
            [DateAdded] => 2018-01-04
            [Total] => 3
        )

    [18] => Array
        (
            [usergroup] => Austin_Domestic
            [DateAdded] => 2018-02-01
            [Total] => 31
        )

    [19] => Array
        (
            [usergroup] => Austin_International
            [DateAdded] => 2018-02-19
            [Total] => 2
        )

    [20] => Array
        (
            [usergroup] => Bangkok
            [DateAdded] => 2018-02-07
            [Total] => 1
        )

    [21] => Array
        (
            [usergroup] => BayArea_Domestic
            [DateAdded] => 2018-02-08
            [Total] => 165
        )

    [22] => Array
        (
            [usergroup] => BayArea_International
            [DateAdded] => 2018-02-12
            [Total] => 29
        )

Here is my code: 这是我的代码:

$selectallmonthlysql = 'SELECT locations, DateAdded, COUNT(*) as Total
                    FROM testserverdataSignup
                    WHERE DateAdded > "2017-12-31"
                    GROUP BY month(DateAdded), locations';

    $selectAllmonthlystmt = $dbo->prepare($selectallmonthlysql);

    $selectAllmonthlystmt->execute();

    $selectAllmonthlylocations = $selectAllmonthlystmt->fetchAll(PDO::FETCH_ASSOC);

Screenshot of what the table currently looks like: I want the individual count for each location to correlate to the month and go across instead of down 该表目前的样子截图:我希望每个位置的个人计数与月份相关,而不是向下

在此输入图像描述

First change your query 首先更改您的查询

$selectallmonthlysql = '
SELECT
    locations,
    MONTHNAME(DateAdded) AS month,
    COUNT(*) AS total
FROM    
    testserverdataSignup
WHERE
    DateAdded > "2017-12-31"
GROUP BY month(DateAdded),locations';

I lowercased Total to total , its something that was irritating me. 我将Totaltotal ,这让我很恼火。

With PDO then you can do 有了PDO,你就可以做到

$results = $selectAllmonthlystmt->fetchAll(PDO::FETCH_GROUP);
foreach($results AS $location => $row ){

FETCH_GROUP is poorly documented but this will organize your data with the first column as the Key of the nested array, in this case the location, which is exactly what we want. FETCH_GROUP的文档记录很少但是这会将第一列的数据组织为嵌套数组的键,在本例中是位置,这正是我们想要的。 One of the reasons I use PDO instead of that other DB library I won't mention by name but it starts with MySql and ends with i . 我使用PDO而不是其他DB库的原因之一我不会提到名称但它以MySql开头并以i结尾。

MONTHNAME (click for documentation) will return the full name of the month like "February" which although is not necessary (just a number would do) its much easier to read when outputting the array for debugging. MONTHNAME (单击以获取文档)将返回月份的全名,如“二月”,虽然不是必需的(只是一个数字可以),但在输出数组进行调试时更容易阅读。

You'll wind up with something like this 你会结束这样的事情

//canned example data, notice one month is out of order and the big gap
// between February to October, this is to show it properly orders and
//fills those in. Always best to test this situations.
$result = array(
   "Austin_Domestic" => array(

       0 => Array(
            "month" => "February",
            "total" => 5
        ),
       1 => Array(
            "month" => "January",
            "total" => 15
        ),
        2 => Array(
            "month" => "October",
            "total" => 8
        ),

    ),
);
//$results = $selectAllmonthlystmt->fetchAll(PDO::FETCH_GROUP);

//then putting it all together

//we'll need the months in an array anyway so we can saves some space with them in the HTML  too.
$months = array(    
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December"
)

?>

<table id="registeredTable" class="table table-striped table-bordered table-hover">
<thead>
    <tr>
        <th>Locations</th>
        <?php foreach($months as $month){
             //Output the names of the months
             echo "<th>{$month}</th>\n";
        } ?>
        </tr>
    </thead>
    <tbody>
    <?php 
        foreach( $result as $location => $rows ){
             echo "<tr>\n";
             echo "<td>{$location}</td>\n";
            //simplifies lookup by month (indexes are correlated)
            //it returns column 'month' from $rows as a flat array.
            //we can save ourselves an external loop by doing this "trick"
            $m = array_column($rows, 'month');
            //for example, in the case: [0=>February,1=>January,2=>October]
            //because this is created from $rows, with a natural number index
            //we can simply do array_search on $m to get the index we need in $rows (see below)
            foreach($months as $month){
                $index = array_search($month, $m);
                if(false === $index){
                    echo "<td>0</td>\n";
                }else{
                   echo "<td>{$rows[$index]['total']}</td>\n"; 
                }                 
            }
            echo "</tr>\n";
        }
    ?>
    </tbody>
</table>

Output (I did format it to look a bit nicer): 输出(我把它格式化得看起来更好一些):

<table id="registeredTable" class="table table-striped table-bordered table-hover">
    <thead>
        <tr>
            <th>Locations</th>
            <th>January</th>
            <th>February</th>
            <th>March</th>
            <th>April</th>
            <th>May</th>
            <th>June</th>
            <th>July</th>
            <th>August</th>
            <th>September</th>
            <th>October</th>
            <th>November</th>
            <th>December</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Austin_Domestic</td>
            <td>15</td>
            <td>5</td>
            <td>0</td>
            <td>0</td>
            <td>0</td>
            <td>0</td>
            <td>0</td>
            <td>0</td>
            <td>0</td>
            <td>8</td>
            <td>0</td>
            <td>0</td>
        </tr>
    </tbody>
</table>

Sandbox 砂箱

One note and benefit of using an array for the months is you spelled Feburary wrong it should be February something I've been guilty of many many times. 几个月使用阵列的一个注意事项和好处是你FeburaryFebruary Feburary应该是February我已多次犯了罪。

The only real downside to this, is the month name has to match the month name returned from the DB, which shouldn't be an issue if they are spelled correctly (which is how I found the mistake). 这个唯一真正的缺点是,月份名称必须与从DB返回的月份名称相匹配,如果拼写正确(这就是我发现错误的方式),这应该不是问题。 Otherwise this can applied to the month as a number just as easily, same idea. 否则这可以作为一个数字同样容易地应用于月份,同样的想法。

Cheers! 干杯!

First, you should change the query to return MONTH(DateAdded) instead of the whole date, since that's how your output table is organized: 首先,您应该更改查询以返回MONTH(DateAdded)而不是整个日期,因为这是输出表的组织方式:

$selectallmonthlysql = 'SELECT locations, MONTH(DateAdded) AS month, COUNT(*) as Total
                FROM testserverdataSignup
                WHERE DateAdded > "2017-12-31"
                GROUP BY month, locations';

Then you should reorganize the array into nested arrays: 然后,您应该将数组重新组织为嵌套数组:

array(location1 => array(month1 => total1, month2 => total2, ...),
      location2 => array(month1 => total1, month2 => total2, ...),
      ...)

This code will do that: 这段代码会这样做:

$groupedData = array();
while ($selectAllmonthlystmt->fetch(PDO::FETCH_ASSOC) {
    $groupedData[$row['locations']][$row['month']] = $row['Total'];
}

Then you can use nested loops when creating the table. 然后,您可以在创建表时使用嵌套循环。 The outer loop creates the rows, the inner loop is for the cells in the row. 外循环创建行,内循环用于行中的单元格。

foreach ($groupedData as $location => $locationData) {
    echo "<tr><td>$location</td>";
    for ($month = 1; $month <= 12; $month++) {
        echo "<td>";
        echo isset($locationData[$month]) ? $locaitonData[$month] : 0;
        echo "</td>";
    }
    echo "</tr>";
}

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

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