简体   繁体   English

PHP 2D阵列故障

[英]PHP 2D array failure

I feel quite stupid for asking this as I feel I should have been able to figure this out, but alas I am spending too much time on it and getting frustrated, so I figured I would request some help. 我问这个问题很愚蠢,因为我认为自己应该能够解决这个问题,但是a,我花了太多时间在它上面并且感到沮丧,所以我想寻求帮助。 I have a PHP array that looks as follows. 我有一个如下所示的PHP数组。 This is just an example as this project is a work in progress: 这只是一个示例,因为该项目正在进行中:

$donations = array(
    "2018 December" => array('30','20','100'),
    "2018 November" => array('10','5','200','1000')
);

I have made several attempts at nested for and foreach loops to try to get the values out, and I can get close, but I always seem to run into different road blocks. 我在嵌套的for和foreach循环中进行了几次尝试,以尝试获取值,并且可以接近,但是我似乎总是遇到不同的障碍。 For example, I used to have the year and months as part of the sub array. 例如,我以前把年和月作为子数组的一部分。 I was able to successfully pull all the values out using a for and then foreach loop, but I could not figure out how to exclude the first two elements (year and month) in the foreach. 我能够使用for然后foreach循环成功提取所有值,但是我不知道如何在foreach中排除前两个元素(年和月)。 Here is the ultimate goal... 这是最终目标...

Each sub array contains individual member donations in US dollars. 每个子阵列均包含以美元为单位的个人捐款。 The array may grow during the current month as more donations come in, but once the month rolls over, the next month sub array starts populating with donations and the previous month is "archived". 随着更多捐款的到来,该数组可能会在当前月份增长,但是当该月结束时,下个月的子数组将开始使用捐款进行填充,并且上个月将被“存档”。 I need to sum all the donations for each sub array and make each value available to be represented as a percentage (round to nearest integer) as part of a bar graph that displays on the webpage. 我需要汇总每个子数组的所有捐赠,并使每个值都可以用百分比表示(四舍五入到最接近的整数),作为显示在网页上的条形图的一部分。

Can anyone please help me to formalize my process? 谁能帮我使我的程序正规化吗?

This is what I tried initially. 这是我最初尝试的。 This is using the older uglier array. 这使用的是较旧的较丑陋的数组。 It should be noted, this version currently does not round to nearest integer. 应该注意的是,该版本当前无法四舍五入到最接近的整数。 Have not figured that part out yet either. 也没有弄清楚那部分。 These numbers just workout nicely in this example. 在此示例中,这些数字很好地锻炼了身体。 Also, in case you are curious, $total is calculated separately in a different part of the page. 另外,如果您感到好奇,可以在页面的不同部分分别计算$ total。 $total = the operating costs per month for the group, but in this example I have manually set it to $100. $ total =该组每月的运营成本,但是在此示例中,我手动将其设置为$ 100。

$donate = array(
    array("5","10"),
    array("20","30"),
    array("0"),
    array("0"),
    array("0")
);

$keydonate = array_keys($donate);
$taco = array();
for($i = 0; $i < count($donate); $i++) {
    foreach($donate[$keydonate[$i]] as $value) {
        $sum = $sum + $value;
        $taco[$i] = ($sum/$total)*100;
    }
}

This kinda works, but again, my logic is severely flawed here and this method has some pretty serious bugs. 这种方法有效,但同样,我的逻辑在此存在严重缺陷,并且该方法存在一些非常严重的错误。 For example, the arrays keep adding to each other from previous months. 例如,阵列从前几个月开始彼此增加。 Every month they need to reset back to default. 他们每个月都需要重置为默认值。 Notice how in the screen shot, December is actually a sum of December and November and then on and on? 请注意,在屏幕截图中,十二月实际上是十二月和十一月的总和,然后又是又一个又一个? Also, I like being able to add the month and year to the array as well, which this version is not capable of handling. 另外,我也希望能够将月份和年份也添加到数组中,而该版本无法处理。 I need some serious guidance and examples on the proper way to do this please. 我需要一些认真的指导和示例,以帮助您找到正确的方法。 I know just enough PHP to be dangerous! 我知道足够多的PHP才是危险的!

Thank you! 谢谢!

进度条

You were really close. 你真的很亲近

It looks like the only reason the code you tried wasn't working was that you weren't resetting the sum to zero for each month. 您尝试的代码无法正常工作的唯一原因似乎是您没有将每个月的总和重置为零。

for($i = 0; $i < count($donate); $i++) {
    $sum = 0;                                        // <----- Like this
    foreach($donate[$keydonate[$i]] as $value) {
        $sum = $sum + $value;
        $taco[$i] = ($sum/$total)*100;
    }
}

There are some other things that could be optimized, but that should be all you need to get it working. 还有其他一些可以优化的东西,但这应该是使它工作所需的全部。


Some suggestions for optimization: 一些优化建议:

It's generally better to use a foreach loop to iterate an array. 通常最好使用foreach循环来迭代数组。 A for loop is generally better for doing something a fixed number of times. 对于执行固定次数的操作,for循环通常更好。 And calculating the percentage inside the inner loop is a bit wasteful (you're recalculating it for every number in the inner array, but only using the last one). 而且,计算内部循环中的百分比有点浪费(您需要对内部数组中的每个数字重新计算它,但只能使用最后一个数字来重新计算)。 You can calculate it after that loop ends instead. 您可以在循环结束后进行计算。

foreach ($donate as $month => $values) {
    $sum = 0;
    foreach($values as $value) {
        $sum += $value;
    }
    $taco[$month] = ($sum/$total)*100;
}

Or even better, use a built in function to sum the inner array instead of another loop. 甚至更好的是,使用内置函数对内部数组求和而不是另一个循环。

foreach ($donate as $month => $values) {
    $taco[$month] = array_sum($values) / $total * 100;
}

I added the month and year into the array like you said you wanted and make this little script that seems to do what you are asking if I understood your question correctly. 我像您说的那样将月份和年份添加到数组中,并制作了这个小脚本,它似乎可以解决您所要询问的问题,如果我正确理解了您的问题。

<?php
        //Enter your code here, enjoy!

$donations = array(
    array('2018', 'December', '30','20','100'),
    array('2018', 'November', '10','5','200','1000')
);

$total = 75;


$taco = array();
for($i = 0; $i < count($donations); $i++) {
    $sum = 0;
    for($j = 2; $j < count($donations[$i]); $j++) {
        $sum += $donations[$i][$j];
        }
        //echo $sum." ";
    $taco[$i] = ($sum/$total)*100;
}

for($i = 0; $i < count($donations); $i++){
    echo "Month ". $donations[$i][0]." ".$donations[$i][1]." raised ".$taco[$i]." % of monthly costs."."\r\n";
}

Is this more what your looking for? 这更多是您想要的吗? Output: 输出: 在此处输入图片说明

Well I wish the original guy that gave me this answer would not have deleted his post. 好吧,我希望给我这个答案的原始人不会删除他的帖子。 The solution was correct! 解决方法是正确的! I just had to make a slight modification to suit my purposes. 我只需要稍作修改即可适合我的目的。 Here is the working solution with screenshot. 这是带有屏幕截图的有效解决方案。 Thank you mystery user! 谢谢神秘用户! Thank you everyone else too for your time and submissions. 也感谢其他所有人的时间和意见。

<?php
    //------------ MEMBER DONATIONS ------------
    $donations = [
        "2019 March" => ['100','8.61'],
        "2019 February" => ['0.12','0.45','1.76','4.23','1.23','9.34','2.34','1.23','5.55','9.21'],
        "2019 January" => ['10','10','10','10','5'],
        "2018 December" => ['0'],
        "2018 November" => ['10']
    ];
    //------------------------------------------

    $totalSum = 0;
    $monthlySums = [];
    $monthlyPercentages = [];
    foreach($donations as $month => $values) {
        $monthlySums[$month] = array_sum($values);
        $totalSum += $monthlySums[$month];
    }
    foreach($monthlySums as $month => $monthlySum) {
        $monthlyPercentages[$month] = round($monthlySum / $total * 100,2);
        if($monthlyPercentages[$month] > 100){
            $monthlyPercentages[$month] = 100;
        }
    }
?>

and then the HTML 然后是HTML

    <?php
        foreach(array_keys($donations) as $month) {
            echo "<div class='prog-font'>". $month ."</div><div class='prog-cont'><div class='prog-fill' style='width:". $monthlyPercentages[$month] ."%'><span style='padding-left: 5px;'>". $monthlyPercentages[$month] ."%</span></div></div><div class='prog-goal'>Operating Expenses $". $total ."</div><br />";
        };
    ?>

在此处输入图片说明

I decided to allow two decimal places and I decided to include some simple limits to prevent the bar graph from spilling over. 我决定允许两位小数,并决定包括一些简单的限制以防止条形图溢出。 Ideally once one month is fully funded, the remainder would spillover to the next month, but for the time being I will deal with that manually. 理想情况下,一个月一旦有足够的资金,其余的将溢出到下个月,但暂时我将手动处理。 Will work on additional automation at a later date. 以后将用于其他自动化。 Just nice to have this initially up and running. 最初启动并运行它真是太好了。 Thank you! 谢谢!

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

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