PHP数组\u密钥\u存在,无法正常工作
我有一个php脚本,应该为ip地址分配虚拟名称PHP数组\u密钥\u存在,无法正常工作,php,json,file-get-contents,array-key-exists,Php,Json,File Get Contents,Array Key Exists,我有一个php脚本,应该为ip地址分配虚拟名称 <?php function generateRandomString($length = 10) { $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $charactersLength = strlen($characters); $randomString = ''; for ($i = 0; $
<?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);
}
?>
但在这种情况下,file\u get\u内容无法正常工作。
请帮忙
array\u key\u exists
仅用于数组,而$json
变量包含一个对象
将$json
更改为对象的数组
或使用属性_exists
将$json转换为数组的示例
$json = json_decode($read, true);
var_dump($read)
它说什么?访问文件时可能存在权限问题,array\u key\u存在
仅检查数组的第一个维度,因此您需要显示$json
的数据结构以查看其深度。var\u dump($read)
读取它应该读取的内容string(2)“{}”
$json的值是一个一维关联数组。上面写着,{}。我两个都试过了。它不起作用。我很确定$json是一个关联数组,但我不确定。我尝试使用var\u转储存在的``array\u key`($\u SERVER[“REMOTE\u ADDR”],$json)````,它返回NULL,而不是布尔值。我重写了整个代码,结果成功了。也许我拼错了什么。
$json = json_decode($read, true);