我必须创建一个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;
的行中收到错误。
因此,当用户选择一年时,它应该通过与年份相关联的数字来识别它。因此,例如,如果他们选择1790和1800,那么1800应该减去1790,但不是实际年份,与该年相关的数字如下:5236631 - 3929214,答案应该是1307417 我将这些年与数字联系起来的方式是否有问题?
答案 0 :(得分:1)
你的变量是同名的所以它绝对不会起作用。这意味着你在这里增加数组和各种各样的东西。大概你正在尝试做类似的事情:
"error": {
"message": "Can't Load URL: The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and subdomains of your app to the App Domains field in your app settings.",
"type": "OAuthException",
"code": 191,
"fbtrace_id": "CwaEPJ4+X8p"
}
1790年和1800年,我所拥有的应该给你:
<?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
));
}