php - 如何更新使用已弃用的 each() 函数的代码?

标签 php each

在 PHP 7.2 中,each 已弃用。 The documentation说:

Warning This function has been DEPRECATED as of PHP 7.2.0. Relying on this function is highly discouraged.

如何更新我的代码以避免使用它?以下是一些示例:

  1. >
    $ar = $o->me;
    reset($ar);
    list($typ, $val) = each($ar);
    
  2. >
    $out = array('me' => array(), 'mytype' => 2, '_php_class' => null);
    $expected = each($out);
    
  3. >
    for(reset($broken);$kv = each($broken);) {...}
    
  4. >
    list(, $this->result) = each($this->cache_data);
    
  5. >
    // iterating to the end of an array or a limit > the length of the array
    $i = 0;
    reset($array);
    while( (list($id, $item) = each($array)) || $i < 30 ) {
        // code
        $i++;
    }
    

当我在 PHP 7.2 上执行代码时,我收到以下错误:

Deprecated: The each() function is deprecated. This message will be suppressed on further calls

最佳答案

  1. 对于前两个示例,您可以使用 key()current() 来分配您需要的值。

    $ar = $o->me;   // reset isn't necessary, since you just created the array
    $typ = key($ar);
    $val = current($ar);
    
  2. >
    $out = array('me' => array(), 'mytype' => 2, '_php_class' => null);
    $expected = [key($out), current($out)];
    

    在这些情况下,您可以使用 next() 使光标在之后前进,但如果您的其余代码不依赖于此,则可能没有必要。

  3. 对于第三种情况,我建议只使用 foreach() 循环,并在循环内分配 $kv

    foreach ($broken as $k => $v) {
         $kv = [$k, $v];
    }
    
  4. 对于第四种情况,在 list() 中似乎忽略了键,因此您可以分配当前值。

    $this->result = current($this->cache_data);
    

    与前两种情况一样,可能需要使用 next() 推进光标,具体取决于其余代码与 $this->cache_data 的交互方式.

  5. 第五个可以替换为 for() 循环。

    reset($array);
    for ($i = 0; $i < 30; $i++) {
        $id = key($array);
        $item = current($array);
        // code
        next($array);
    }
    

关于php - 如何更新使用已弃用的 each() 函数的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48716437/

相关文章:

javascript - 即使包含 timepicker css 和 js 文件,$(...).timepicker 也不是函数错误?

jQuery 在 .each() 中操作对象

javascript - 查询。使用 ajax 调用在 .each 循环之后调用函数

php - mysql 仅选择下周数据

php - 如何在PHP中实现事件监听

javascript - 我需要刷新我的页面来更新文本区域,即使我以与以前相同的方式设置文本

javascript - 从每个循环中运行函数(ajax.response)

javascript - underscore _.each 和 forEach 有什么区别?

javascript - jQueryeach与replaceWith结合问题

php - 保留更改 MySQL