PHP:像在Python中一样获取数组值?

dur*_*ara 15 php python arrays default get

在Python中,我可以使用"get"方法从字典中获取值而不会出错.

a = {1: "a", 2: "b"}
a[3] # error
a.get(3, "") # I got empty string.
Run Code Online (Sandbox Code Playgroud)

所以我搜索一个执行此操作的common/base函数:

function GetItem($Arr, $Key, $Default){
    $res = '';
    if (array_key_exists($Key, $Arr)) {
        $res = $Arr[$Key];
    } else {
        $res = $Default;
    }
    return $res;
}
Run Code Online (Sandbox Code Playgroud)

在PHP中基本具有与Python相同的功能吗?

谢谢:dd

Mic*_*ski 10

isset()通常比...更快array_key_exists().$default如果省略,则将参数初始化为空字符串.

function getItem($array, $key, $default = "") {
  return isset($array[$key]) ? $array[$key] : $default;
}

// Call as
$array = array("abc" => 123, "def" => 455);
echo getItem($array, "xyz", "not here");
// "not here"
Run Code Online (Sandbox Code Playgroud)

但是,如果存在数组键但具有NULL值,isset()则不会按预期方式运行,因为它会将其NULL视为不存在并返回$default.如果您希望NULL数组中的s,则必须使用array_key_exists().

function getItem($array, $key, $default = "") {
  return array_key_exists($key, $array) ? $array[$key] : $default;
}
Run Code Online (Sandbox Code Playgroud)

  • 我创建了另一个更简单且需要更少参数的辅助函数:http://stackoverflow.com/a/25205195/1890285 (2认同)