【问题标题】:PHP array_key_exists not working correctlyPHP array_key_exists 无法正常工作
【发布时间】:2021-08-16 22:07:43
【问题描述】:

我有一个应该为 IP 地址分配虚拟名称的 php 脚本。

<?php
function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}
$read = file_get_contents("vnames.json");
$json = json_decode($read);
var_dump($_SERVER["REMOTE_ADDR"]);
if(!array_key_exists($_SERVER["REMOTE_ADDR"], $json)){
    $json[$_SERVER["REMOTE_ADDR"]] = generateRandomString();
    $read = json_encode($json);
    echo "This if statement is true!";
    file_put_contents("vnames.json", $read);
}
?>

names.json 里面只有一对空括号。

所以,我发现!array_key_exists($_SERVER["REMOTE_ADDR"], $json) 是错误的。但是,我确定 names.json 不包含我的 IP 地址。 我假设这是正在评估的内容:

<?php
function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}
$read = file_get_contents("vnames.json");//blank
$json = json_decode($read);//null
var_dump($_SERVER["REMOTE_ADDR"]);//My ip
if(!array_key_exists($_SERVER["REMOTE_ADDR"], $json)/*false*/){
    $json[$_SERVER["REMOTE_ADDR"]] = generateRandomString();
    $read = json_encode($json);
    echo "This if statement is true!";
    file_put_contents("vnames.json", $read);
}
?>

但在这种情况下,file_get_contents 无法正常工作。 请帮忙!

【问题讨论】:

  • var_dump($read); 它说什么?
  • 访问文件可能存在权限问题,
  • array_key_exists 只检查数组的第一个维度,所以你需要展示$json 的数据结构才能看到它有多深。
  • var_dump($read) 读取它应该读取的内容。 string(2) "{}"
  • $json 的值是一维关联数组。它的内容是,{}。

标签: php json file-get-contents array-key-exists


【解决方案1】:

array_key_exists 仅适用于数组,而$json 变量包含一个对象。

要么将$json 更改为array,要么将property_exists 用于对象。

将 $json 转换为数组的示例

$json = json_decode($read, true);

【讨论】:

  • 这两件事我都试过了。它没有用。我很确定 $json 是一个关联数组,但我不确定。我尝试 var_dumping ``` array_key_exists($_SERVER["REMOTE_ADDR"], $json) ```,它返回 NULL,而不是布尔值。
  • 我重写了我的整个代码并且它成功了。也许我拼错了什么。
猜你喜欢
  • 1970-01-01
  • 2015-11-15
  • 1970-01-01
  • 2019-01-13
  • 2012-10-28
  • 2013-10-13
  • 2012-12-06
  • 1970-01-01
  • 2016-01-19
相关资源
最近更新 更多