each() 已弃用,摆脱麻烦

each() deprecated, trouble to get rid of

我正在使用 sql 数据库备份脚本,在我的部分代码中:

if (!isset($table_select))
{
$result = $dbc->prepare("show tables");
$i=0;
$table="";
$tables = $dbc->executeGetRows($result);
foreach ($tables as $table_array)
{
list(,$table) = each($table_array);
$exclude_this_table = isset($table_exclude)? in_array($table,$table_exclude) : false;
if(!$exclude_this_table) $table_select[$i]=$table;
$i++;
}
}

我不知道如何去掉这部分:list(,$table) = each($table_array);

由于 each() 已弃用,有人知道解决方案吗?
非常感谢!

您不想在 php 脚本中执行此操作。我强烈建议尽可能使用一些 cronjob 来完成这项任务。

您可以使用

创建一个 cronjob
crontab -e

并添加如下内容:

0 1 * * * mysqldump -e --user=username --password='password' dbname | gzip | uuencode
sql_backup.gz | mail example@example.com

以上示例将在每天凌晨 1 点启动作业。

您可以在此处查看 manual

希望对您有所帮助! :)

由于您没有使用 each 提供的密钥,因此在此上下文中不需要它。

示例:https://3v4l.org/8vie4

由于数组是通过复制而不是通过引用传递的,因此如果您不在同一上下文中再次使用 $table_array,则可以使用 array_shift() 作为替代方法。

foreach ($tables as $table_array) {
    $table = array_shift($table_array);
    var_dump($table);
}

记住 array_shift 检索当前值,并将其从数组中删除。

由于each()检索当前键值对并将指针前进到下一个值,您可以将其替换为current()next()

foreach ($tables as $table_array) {
    $table = current($table_array);
    var_dump($table);
    next($table_array);
}

如果在使用currentnext时确实需要当前值的key,您可以使用key()

foreach ($tables as $table_array) {
    $key = key($table_array);
    $table = current($table_array);
    var_dump($key, $table);
    next($table_array);
}

由于您使用的自动备份脚本使用 PDO,您可以使用 fetchAll(PDO::FETCH_COLUMN); 而不是 executeGetRows 来降低复杂性,后者将检索 0 索引列的平面数组与列键值对相对。

$result = $dbc->prepare("show tables");
$result->execute();
$i=0;
$table="";
$tables = $result->fetchAll(\PDO::FETCH_COLUMN);
foreach ($tables as $table) {
     //...
}