PHP关联数组。使用foreach获取键值对

时间:2016-06-28 16:54:26

标签: php foreach associative-array

我正在尝试定义一个函数,给定一个关联数组,在给定该函数的参数的情况下,它将回显键值对。

到目前为止,我的代码如下所示。但是,该代码的结果将是键值对的完整列表(表)。我想要的只是一对(一旦调用函数)。

有人能帮助我吗?

谢谢!

enter code here

<!DOCTYPE html>
<html>
<head>

<body>

<h1>List of States</h1>

<?php

$states = array ("AL"=>"Alabama","AK"=>"Alaska","AZ"=>"Arizona","AR"=>"Arkansas","CA"=>"California","CO"=>"Colorado","CT"=>"Connecticut",
"DE"=>"Delaware","FL"=>"Florida","GA"=>"Georgia","HI"=>"Hawaii","ID"=>"Idaho","IL"=>"Illinois","IN"=>"Indiana","IA"=>"Iowa","KS"=>"Kansas",
"KY"=>"Kentucky");

function printState($Abbr) {

    global $states;

        echo "<table border=1>";

    foreach($states as $Abbr => $value) {   

        echo "<tr>";
        echo "<td>";
        echo $Abbr;
        echo "</td>";
        echo "<td>";
        echo $value;
        echo "</td>";
        echo "</tr>";

    }

        echo "</table>";

}

printState("CA");


?>

</body>
</html>

2 个答案:

答案 0 :(得分:4)

如果你必须有一个功能:

function getState($code) {
    global $states;
    if (array_key_exists($code, $states)) {
        return $states[$code];
    }
    return false;
}

echo getState('GA');

但正如Dave Chen建议的那样,$states[$abbr];就是你如何做到的。

答案 1 :(得分:0)

您好您也可以使用此

function printState($Abbr) {
    global $states;
if (array_key_exists($Abbr,$states)){   
    return "<table border=1><tr><td>$Abbr</td><td>$states[$Abbr]</td></tr></table>";
    }
}
echo printState("AK");
?>