【问题标题】:Remove key from list从列表中删除密钥
【发布时间】:2016-11-09 06:22:32
【问题描述】:

我正在开发一个销售软件许可证密钥的小功能。基本上它的作用是从 txt 中获取密钥,然后获取密钥并删除文件,重写它但没有出售的密钥。不过我有一个问题。谁能帮我发现错误并帮助我修复它?

file.txt 内容:

KEY1, KEY2, KEY3, KEY4, KEY5

我的班级:

class Key {

 public static function getRandomKey($keyset)
 {
    $i = rand(0, count($keyset));
    return $keyset[$i];
 }

}

我的功能:

$file = 'file.txt';
$contents = file_get_contents($file);
$contents = str_replace(' ', '', $contents);
$keyset = explode(',', $contents);
$key = Key::getRandomKey($keyset);
echo $key;
$str = implode(',', $keyset);
unlink($file);
$rfile = fopen($file, 'w');
fwrite($rfile, $str);
fclose($rfile);

【问题讨论】:

  • 您真的需要在文件中执行此操作吗?使用数据库会让事情变得更容易。
  • @andrewsi 我将在项目启动时使用数据库,出于测试目的,我正在使用文件。
  • 好吧,你没有测试在这种情况下你会做什么

标签: php arrays explode implode


【解决方案1】:

我支持@andrewsi's comment,但您想要实现这一目标的一般流程是这样的:

// fetch
$keys = file_get_contents('your_keys.txt');
// explode
$list = explode(",", $keys);
// get random key (this would be your Key::getRandomKey() function)
$use = rand(0, (count($list) - 1)); // notice how we do count($list) - 1? Since the index starts at 0, not 1, you need to account for that ;-)

// now get a key
echo $list[$use];
// unset that key from the list
unset($list[$use]);
// implode the keys again
$keys = implode(", ",$list);
// and save it to the file
file_put_contents('your_keys.txt', $keys);

Example/Demo

【讨论】:

  • 你可以使用array_rand$use = àrray_rand($list)
  • @IsmailRBOUH 你 100% 可以(这可能是更简单的解决方案) - 坚持 OP 的原始问题范围 :)
  • 谢谢,您的代码正在运行,只是为了扩展我的知识,您真的发现了错误吗?我也将代码更改为 array_rand
  • @Stunked 你从来没有从原始的$keyset 数组中删除它——注意我是如何使用unset() 的?之后,将其写入文件:)
  • @Darren 谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-27
  • 2011-10-07
  • 1970-01-01
相关资源
最近更新 更多