Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/227.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP7.2已弃用:while=不带$value的each()循环_Php_Foreach_While Loop_Each_Deprecated - Fatal编程技术网

PHP7.2已弃用:while=不带$value的each()循环

PHP7.2已弃用:while=不带$value的each()循环,php,foreach,while-loop,each,deprecated,Php,Foreach,While Loop,Each,Deprecated,由于each()循环由于PHP7.2而被弃用,当(()=each())循环没有$value时,如何更新下面的 没有$value我就无法让foreach循环工作。此外,而($products\u id=$this->contents)导致无限循环 谢谢大家! $total_items = 0; reset($this->contents); while (list($products_id, ) = each($this->contents)) { $total_items

由于each()循环由于PHP7.2而被弃用,当(()=each())循环没有$value时,如何更新下面的

没有$value我就无法让foreach循环工作。此外,而($products\u id=$this->contents)导致无限循环

谢谢大家!

$total_items = 0;

reset($this->contents);
while (list($products_id, ) = each($this->contents)) {
    $total_items += $this->get_quantity($products_id);
}

以下是一些方法:

标准的
foreach
循环(非常可读):

或者,减少:

$total_items = array_reduce($this->contents, function($acc, $item) {
    return $acc + $this->get_quantity($products_id[0]);
});
或者,在函数表达式中:

$total_items = array_sum(array_map([$this, 'get_quantity'],
                         array_column($this->contents, 0)));

这些方法都不需要重置($this->contents)在它前面。

我找到了修复它的方法,并想与大家分享信息。下面还有一些关于如何将each()循环升级到foreach()的其他案例

案例1:缺少$value 更新至:

foreach(array_keys($array) as $key) {
foreach($array as $value) {
foreach($array as $key => $value) {
案例2:缺少$key 更新至:

foreach(array_keys($array) as $key) {
foreach($array as $value) {
foreach($array as $key => $value) {
案例3:没有遗漏任何东西 更新至:

foreach(array_keys($array) as $key) {
foreach($array as $value) {
foreach($array as $key => $value) {
要详细说明案例3的优秀正确答案,请执行以下操作:

下面是“案例3”情况的完整示例,因为我发现完整示例的信息量远远大于一行代码片段:

这是来自第三方旧代码库(TCPDF)的正版代码

不赞成: 固定的: 更新至:

foreach(array_keys($this->contents) as $products_id) {
  $total_items += $this->get_quantity($products_id);
}
foreach($this->contents as $key =>$value) {
  $total_items += $this->get_quantity($products_id);
}
其他条件:

foreach(array_keys($this->contents) as $products_id) {
  $total_items += $this->get_quantity($products_id);
}
foreach($this->contents as $key =>$value) {
  $total_items += $this->get_quantity($products_id);
}
使用带有闭包的
foreach()
array\u map()
也是可行的。