[英]PHP array_key_exists not working correctly
I have a php script that is supposed to assign virtual names to ip addresses.我有一个 php 脚本,它应该将虚拟名称分配给 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");
$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);
}
?>
Inside names.json, there are is only a pair of empty brackets.在names.json里面,只有一对空括号。
So, I've figured out that ,array_key_exists($_SERVER["REMOTE_ADDR"], $json)
is false.所以,我发现
,array_key_exists($_SERVER["REMOTE_ADDR"], $json)
是错误的。 But, I'm sure that names.json does not contain my IP address.但是,我确定 names.json 不包含我的 IP 地址。 I've assumed that this is is what's being evaluated:
我假设这是正在评估的内容:
<?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);
}
?>
But in that case, file_get_contents is not working correctly.但在这种情况下,file_get_contents 无法正常工作。 Please help!
请帮忙!
array_key_exists
is only for arrays, while the $json
variable contains an object. array_key_exists
仅适用于 arrays,而$json
变量包含 object。
Either change $json
to be an array
or use property_exists
for the object.将
$json
更改为array
或将property_exists
用于 object。
Example to transform $json into an array将 $json 转换为数组的示例
$json = json_decode($read, true);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.