简体   繁体   English

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

[英]PHP Associative array. Get key value pair using foreach

I'm trying to define a function that, given an associative array, would echo the key value pair, given an argument for that function. 我正在尝试定义一个函数,给定一个关联数组,该函数将回显键值对,并给出该函数的参数。

So far I have the code that appears below. 到目前为止,我有下面显示的代码。 However, the result of that code would be a complete list (table) of the key-value pairs. 但是,该代码的结果将是键值对的完整列表(表)。 What I'm trying to get is just ONE pair (once the function is called). 我想要得到的只是一对(一旦调用了函数)。

Could anybody help me? 有人可以帮我吗?

Thanks! 谢谢!

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>

If you must have a function: 如果必须具有功能:

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

echo getState('GA');

But as Dave Chen suggested, $states[$abbr]; 但是正如Dave Chen所建议的那样, $states[$abbr]; is how you'd do it. 是你会怎么做的。

Hi You can also use this 嗨,你也可以使用这个

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");
?>

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

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