如何解决每个PHP已弃用的功能

使用PHP 7.2,each不推荐使用。文件说:


警告此功能自PHP 7.2.0起已废弃。非常不鼓励依赖此功能。


如何更新我的代码以避免使用它?这里有些例子:


$ar = $o->me;

reset($ar);

list($typ, $val) = each($ar);

$out = array('me' => array(), 'mytype' => 2, '_php_class' => null);

$expected = each($out);

for(reset($broken);$kv = each($broken);) {...}

list(, $this->result) = each($this->cache_data);

// 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++;

}


潇潇雨雨
浏览 595回答 3
3回答

茅侃侃

对于前两个示例案例,您可以使用key()和current()分配所需的值。$ar = $o->me;&nbsp; &nbsp;// reset isn't necessary, since you just created the array$typ = key($ar);$val = current($ar);$out = array('me' => array(), 'mytype' => 2, '_php_class' => null);$expected = [key($out), current($out)];在这些情况下,您可以使用next()以后推进光标,但如果其余代码不依赖于此,则可能没有必要。对于第三种情况,我建议只使用foreach()循环而$kv在循环内部分配。&nbsp; &nbsp; foreach ($broken as $k => $v) {&nbsp; &nbsp; &nbsp; &nbsp; $kv = [$k, $v];&nbsp; &nbsp; }对于第四种情况,看起来密钥被忽略list(),因此您可以分配当前值。&nbsp; &nbsp; $this->result = current($this->cache_data);与前两种情况一样,可能需要next()根据代码的其余部分如何与之交互来推进光标$this->cache_data。第五个可以用for()循环代替。&nbsp; &nbsp; reset($array);&nbsp; &nbsp; for ($i = 0; $i < 30; $i++) {&nbsp; &nbsp; &nbsp; &nbsp; $id = key($array);&nbsp; &nbsp; &nbsp; &nbsp; $item = current($array);&nbsp; &nbsp; &nbsp; &nbsp; // code&nbsp; &nbsp; &nbsp; &nbsp; next($array);&nbsp; &nbsp; }

慕慕森

你可以each()使用key(),current()和next()创建自己的函数。然后用该函数替换你的调用,如下所示:<?phpfunction myEach(&$arr) {&nbsp; &nbsp; $key = key($arr);&nbsp; &nbsp; $result = ($key === null) ? false : [$key, current($arr), 'key' => $key, 'value' => current($arr)];&nbsp; &nbsp; next($arr);&nbsp; &nbsp; return $result;}1。$ar = $o->me;reset($ar);list($typ, $val) = myEach($ar);2。$out = array('me' => array(), 'mytype' => 2, '_php_class' => null);$expected = myEach($out);3。for(reset($broken);$kv = myEach($broken);) {...}

慕田峪9158850

reset($array);while (list($key, $value) = each($array)) {UPDATEreset($array);foreach($array as $key => $value) {
打开App,查看更多内容
随时随地看视频慕课网APP