簡體   English   中英

PHP 2維數組:要使用戶輸入2基於2維數組中的值減去用戶輸入1

[英]PHP 2 dimensional array: To make user input 2 subtract user input 1 based on values from 2 dimensional array

我必須創建一個PHP應用程序來計算兩個美國人口普查年之間的人口差異。 人口普查年和人口將以二維數組存儲。 應用程序應計算人口差異並顯示差異。 如果差異為負,則顯示一條反映人口減少的消息。 如果差異為正,則顯示一條消息,指示人口增加。 如果人口沒有變化,則顯示一條消息,指出人口沒有變化。 這是我到目前為止的內容:

<body>
        <form action="handle_census.php" method="post">
            <p>Year 1: <input type="number" name="value1" step="10"  min= "1790" max= "2010" size="5"></p>
            <p>Year 2: <input type="number" name="value2" step="10"  min= "1790" max= "2010" size="5"></p>
            <input type="submit" name="submit" value="submit">
        </form>
    </div>
</body>
</html>

這將處理用戶輸入,其中年份從1790開始,最大值為2010。用戶選擇年份,PHP帖子處理該計算。 這對我不起作用:

<?php 
$yearList1 = $_POST['value1'];
$yearList2 = $_POST['value2'];

$yearList1 = array(
    array("1790", 3929214),
    array("1800", 5236631),
    array("1810", 7239881),

$yearList2 = array(
    array("1790", 3929214),
    array("1800", 5236631),
    array("1810", 7239881),

$yearTotal = $yearList2 - $yearList1;

print $yearTotal;
?>

為了簡單起見,我並沒有在所有年份中都添加,但是在包含$yearTotal = $yearList2 - $yearList1;的行中出現錯誤$yearTotal = $yearList2 - $yearList1;

因此,當用戶選擇年份時,應該通過與該年份關聯的數字來識別它。 因此,例如,如果他們選擇1790和1800,那么1800應該減去1790,而不是實際年份,與該年份關聯的數字如下:5236631-3929214,答案應該是1307417我的方式是否有問題將年份與數字相關聯?

您的變量具有相同的名稱,因此絕對無法使用。 這意味着您要在此處乘以數組和各種各樣的東西。 大概您正在嘗試執行以下操作:

<?php
# First check these are submitted
if(!empty($_POST['value1']) && !empty($_POST['value2'])) {
    # Assign years (you probably want to trim() and check is_numeric() here)
    $year_1 = $_POST['value1'];
    $year_2 = $_POST['value2'];
    # Presumably these are hardcoded otherwise you would isolate using a query
    # instead of grabbing all this list in one giant array
    $years = array(
        array("1790", 3929214),
        array("1800", 5236631),
        array("1810", 7239881)
    );
    # Set defaults here
    $y1 =
    $y2 = 0;
    # Loop first array to get value
    # If you are doing a query, this part is not relevant
    foreach($years as $year) {
        # Determine year matches for year 1 and 2
        if($year[0] == $year_1) {
            $y1 = $year[1];
        }
        if($year[0] == $year_2) {
            $y2 = $year[1];
        }
    }
    # Determine if the years are larger or smaller from year before
    $larger =   ($y1 > $y2);
    # Divide
    $total = ($larger)? ($y2/$y1) : ($y1/$y2);
    # Write the percentage with a plus or minus
    $percent    =   (($larger)? '-':'+').round($total*100,2,PHP_ROUND_HALF_UP).'%';
    # The difference in numbers
    $diff       =   ($larger)? ($y1 - $y2) : ($y2 - $y1);
    # Show both results
    print_r(array(
        'percent'=>$percent,
        'diff'=>(($larger)? '-':'+').$diff
    ));
}

我要用1790和1800給您:

Array
(
    [percent] => +75.03%
    [diff] => +1307417
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM